]> git.saurik.com Git - wxWidgets.git/blame - src/common/zipstrm.cpp
document (and check for it with assert) that wxGetKeyState(WXK_[LMR]BUTTON) doesn...
[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,
549 wxIntegerEqual, _wxOffsetZipEntryMap);
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
WS
562 void RemoveEntry(wxFileOffset key)
563 { m_entries.erase((_wxOffsetZipEntryMap::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;
571 _wxOffsetZipEntryMap m_entries;
572};
573
574wxZipWeakLinks *wxZipWeakLinks::AddEntry(wxZipEntry *entry, wxFileOffset key)
575{
26481315 576 m_entries[(_wxOffsetZipEntryMap::key_type)key] = entry;
00375592
VZ
577 m_ref++;
578 return this;
579}
580
581wxZipEntry *wxZipWeakLinks::GetEntry(wxFileOffset key) const
582{
26481315
WS
583 _wxOffsetZipEntryMap::const_iterator it =
584 m_entries.find((_wxOffsetZipEntryMap::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
687 switch (wxFileName::GetFormat(format)) {
688 case wxPATH_DOS:
689 {
690 wxString name(isDir ? m_Name + _T("\\") : m_Name);
691 for (size_t i = name.length() - 1; i > 0; --i)
692 if (name[i] == _T('/'))
693 name[i] = _T('\\');
694 return name;
695 }
696
697 case wxPATH_UNIX:
698 return isDir ? m_Name + _T("/") : m_Name;
699
700 default:
701 ;
702 }
703
704 wxFileName fn;
705
706 if (isDir)
707 fn.AssignDir(m_Name, wxPATH_UNIX);
708 else
709 fn.Assign(m_Name, wxPATH_UNIX);
710
711 return fn.GetFullPath(format);
712}
713
714// Static - Internally tars and zips use forward slashes for the path
715// separator, absolute paths aren't allowed, and directory names have a
716// trailing slash. This function converts a path into this internal format,
717// but without a trailing slash for a directory.
718//
719wxString wxZipEntry::GetInternalName(const wxString& name,
720 wxPathFormat format /*=wxPATH_NATIVE*/,
721 bool *pIsDir /*=NULL*/)
722{
723 wxString internal;
724
725 if (wxFileName::GetFormat(format) != wxPATH_UNIX)
726 internal = wxFileName(name, format).GetFullPath(wxPATH_UNIX);
727 else
728 internal = name;
729
730 bool isDir = !internal.empty() && internal.Last() == '/';
731 if (pIsDir)
732 *pIsDir = isDir;
733 if (isDir)
734 internal.erase(internal.length() - 1);
735
736 while (!internal.empty() && *internal.begin() == '/')
737 internal.erase(0, 1);
738 while (!internal.empty() && internal.compare(0, 2, _T("./")) == 0)
739 internal.erase(0, 2);
740 if (internal == _T(".") || internal == _T(".."))
741 internal = wxEmptyString;
742
743 return internal;
744}
745
746void wxZipEntry::SetSystemMadeBy(int system)
747{
748 int mode = GetMode();
749 bool wasUnix = IsMadeByUnix();
750
26481315 751 m_SystemMadeBy = (wxUint8)system;
00375592
VZ
752
753 if (!wasUnix && IsMadeByUnix()) {
754 SetIsDir(IsDir());
755 SetMode(mode);
756 } else if (wasUnix && !IsMadeByUnix()) {
757 m_ExternalAttributes &= 0xffff;
758 }
759}
760
761void wxZipEntry::SetIsDir(bool isDir /*=true*/)
762{
763 if (isDir)
764 m_ExternalAttributes |= wxZIP_A_SUBDIR;
765 else
766 m_ExternalAttributes &= ~wxZIP_A_SUBDIR;
767
768 if (IsMadeByUnix()) {
769 m_ExternalAttributes &= ~wxZIP_S_IFMT;
770 if (isDir)
771 m_ExternalAttributes |= wxZIP_S_IFDIR;
772 else
773 m_ExternalAttributes |= wxZIP_S_IFREG;
774 }
775}
776
777// Return unix style permission bits
778//
779int wxZipEntry::GetMode() const
780{
781 // return unix permissions if present
782 if (IsMadeByUnix())
783 return (m_ExternalAttributes >> 16) & 0777;
784
785 // otherwise synthesize from the dos attribs
786 int mode = 0644;
787 if (m_ExternalAttributes & wxZIP_A_RDONLY)
788 mode &= ~0200;
789 if (m_ExternalAttributes & wxZIP_A_SUBDIR)
790 mode |= 0111;
791
792 return mode;
793}
794
795// Set unix permissions
796//
797void wxZipEntry::SetMode(int mode)
798{
799 // Set dos attrib bits to be compatible
800 if (mode & 0222)
801 m_ExternalAttributes &= ~wxZIP_A_RDONLY;
802 else
803 m_ExternalAttributes |= wxZIP_A_RDONLY;
804
805 // set the actual unix permission bits if the system type allows
806 if (IsMadeByUnix()) {
807 m_ExternalAttributes &= ~(0777L << 16);
808 m_ExternalAttributes |= (mode & 0777L) << 16;
809 }
810}
811
812const char *wxZipEntry::GetExtra() const
813{
814 return m_Extra ? m_Extra->GetData() : NULL;
815}
816
817size_t wxZipEntry::GetExtraLen() const
818{
819 return m_Extra ? m_Extra->GetSize() : 0;
820}
821
822void wxZipEntry::SetExtra(const char *extra, size_t len)
823{
824 Unique(m_Extra, len);
825 if (len)
826 memcpy(m_Extra->GetData(), extra, len);
827}
828
829const char *wxZipEntry::GetLocalExtra() const
830{
831 return m_LocalExtra ? m_LocalExtra->GetData() : NULL;
832}
833
834size_t wxZipEntry::GetLocalExtraLen() const
835{
836 return m_LocalExtra ? m_LocalExtra->GetSize() : 0;
837}
838
839void wxZipEntry::SetLocalExtra(const char *extra, size_t len)
840{
841 Unique(m_LocalExtra, len);
842 if (len)
843 memcpy(m_LocalExtra->GetData(), extra, len);
844}
845
846void wxZipEntry::SetNotifier(wxZipNotifier& notifier)
847{
848 wxArchiveEntry::UnsetNotifier();
849 m_zipnotifier = &notifier;
850 m_zipnotifier->OnEntryUpdated(*this);
851}
852
853void wxZipEntry::Notify()
854{
855 if (m_zipnotifier)
856 m_zipnotifier->OnEntryUpdated(*this);
857 else if (GetNotifier())
858 GetNotifier()->OnEntryUpdated(*this);
859}
860
861void wxZipEntry::UnsetNotifier()
862{
863 wxArchiveEntry::UnsetNotifier();
864 m_zipnotifier = NULL;
865}
866
867size_t wxZipEntry::ReadLocal(wxInputStream& stream, wxMBConv& conv)
868{
869 wxUint16 nameLen, extraLen;
870 wxUint32 compressedSize, size, crc;
871
872 wxDataInputStream ds(stream);
873
874 ds >> m_VersionNeeded >> m_Flags >> m_Method;
875 SetDateTime(wxDateTime().SetFromDOS(ds.Read32()));
876 ds >> crc >> compressedSize >> size >> nameLen >> extraLen;
877
878 bool sumsValid = (m_Flags & wxZIP_SUMS_FOLLOW) == 0;
879
880 if (sumsValid || crc)
881 m_Crc = crc;
882 if ((sumsValid || compressedSize) || m_Method == wxZIP_METHOD_STORE)
883 m_CompressedSize = compressedSize;
884 if ((sumsValid || size) || m_Method == wxZIP_METHOD_STORE)
885 m_Size = size;
886
887 SetName(ReadString(stream, nameLen, conv), wxPATH_UNIX);
888
889 if (extraLen || GetLocalExtraLen()) {
890 Unique(m_LocalExtra, extraLen);
891 if (extraLen)
892 stream.Read(m_LocalExtra->GetData(), extraLen);
893 }
894
895 return LOCAL_SIZE + nameLen + extraLen;
896}
897
898size_t wxZipEntry::WriteLocal(wxOutputStream& stream, wxMBConv& conv) const
899{
900 wxString unixName = GetName(wxPATH_UNIX);
901 const wxWX2MBbuf name_buf = conv.cWX2MB(unixName);
902 const char *name = name_buf;
903 if (!name) name = "";
26481315 904 wxUint16 nameLen = (wxUint16)strlen(name);
00375592
VZ
905
906 wxDataOutputStream ds(stream);
907
908 ds << m_VersionNeeded << m_Flags << m_Method;
909 ds.Write32(GetDateTime().GetAsDOS());
ba9bbf13 910
00375592 911 ds.Write32(m_Crc);
26481315
WS
912 ds.Write32(m_CompressedSize != wxInvalidOffset ? (wxUint32)m_CompressedSize : 0);
913 ds.Write32(m_Size != wxInvalidOffset ? (wxUint32)m_Size : 0);
00375592
VZ
914
915 ds << nameLen;
26481315 916 wxUint16 extraLen = (wxUint16)GetLocalExtraLen();
00375592
VZ
917 ds.Write16(extraLen);
918
919 stream.Write(name, nameLen);
920 if (extraLen)
921 stream.Write(m_LocalExtra->GetData(), extraLen);
922
923 return LOCAL_SIZE + nameLen + extraLen;
924}
925
926size_t wxZipEntry::ReadCentral(wxInputStream& stream, wxMBConv& conv)
927{
928 wxUint16 nameLen, extraLen, commentLen;
929
930 wxDataInputStream ds(stream);
931
932 ds >> m_VersionMadeBy >> m_SystemMadeBy;
933
934 SetVersionNeeded(ds.Read16());
935 SetFlags(ds.Read16());
936 SetMethod(ds.Read16());
937 SetDateTime(wxDateTime().SetFromDOS(ds.Read32()));
938 SetCrc(ds.Read32());
939 SetCompressedSize(ds.Read32());
940 SetSize(ds.Read32());
941
942 ds >> nameLen >> extraLen >> commentLen
943 >> m_DiskStart >> m_InternalAttributes >> m_ExternalAttributes;
944 SetOffset(ds.Read32());
ba9bbf13 945
00375592
VZ
946 SetName(ReadString(stream, nameLen, conv), wxPATH_UNIX);
947
948 if (extraLen || GetExtraLen()) {
949 Unique(m_Extra, extraLen);
950 if (extraLen)
951 stream.Read(m_Extra->GetData(), extraLen);
952 }
953
954 if (commentLen)
955 m_Comment = ReadString(stream, commentLen, conv);
956 else
957 m_Comment.clear();
958
959 return CENTRAL_SIZE + nameLen + extraLen + commentLen;
960}
961
962size_t wxZipEntry::WriteCentral(wxOutputStream& stream, wxMBConv& conv) const
963{
964 wxString unixName = GetName(wxPATH_UNIX);
965 const wxWX2MBbuf name_buf = conv.cWX2MB(unixName);
966 const char *name = name_buf;
967 if (!name) name = "";
26481315 968 wxUint16 nameLen = (wxUint16)strlen(name);
00375592
VZ
969
970 const wxWX2MBbuf comment_buf = conv.cWX2MB(m_Comment);
971 const char *comment = comment_buf;
972 if (!comment) comment = "";
26481315 973 wxUint16 commentLen = (wxUint16)strlen(comment);
00375592 974
26481315 975 wxUint16 extraLen = (wxUint16)GetExtraLen();
00375592
VZ
976
977 wxDataOutputStream ds(stream);
978
979 ds << CENTRAL_MAGIC << m_VersionMadeBy << m_SystemMadeBy;
980
26481315
WS
981 ds.Write16((wxUint16)GetVersionNeeded());
982 ds.Write16((wxUint16)GetFlags());
983 ds.Write16((wxUint16)GetMethod());
00375592
VZ
984 ds.Write32(GetDateTime().GetAsDOS());
985 ds.Write32(GetCrc());
26481315
WS
986 ds.Write32((wxUint32)GetCompressedSize());
987 ds.Write32((wxUint32)GetSize());
00375592
VZ
988 ds.Write16(nameLen);
989 ds.Write16(extraLen);
990
991 ds << commentLen << m_DiskStart << m_InternalAttributes
992 << m_ExternalAttributes << (wxUint32)GetOffset();
ba9bbf13 993
00375592
VZ
994 stream.Write(name, nameLen);
995 if (extraLen)
996 stream.Write(GetExtra(), extraLen);
997 stream.Write(comment, commentLen);
998
999 return CENTRAL_SIZE + nameLen + extraLen + commentLen;
1000}
1001
1002// Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1003// the 1st value is the signature then it is probably an info-zip record,
1004// though there is a small chance that it is in fact a pkzip record which
1005// happens to have the signature as it's CRC.
1006//
1007size_t wxZipEntry::ReadDescriptor(wxInputStream& stream)
1008{
1009 wxDataInputStream ds(stream);
ba9bbf13 1010
00375592
VZ
1011 m_Crc = ds.Read32();
1012 m_CompressedSize = ds.Read32();
1013 m_Size = ds.Read32();
1014
1015 // if 1st value is the signature then this is probably an info-zip record
1016 if (m_Crc == SUMS_MAGIC)
1017 {
1018 char buf[8];
1019 stream.Read(buf, sizeof(buf));
1020 wxUint32 u1 = CrackUint32(buf);
1021 wxUint32 u2 = CrackUint32(buf + 4);
ba9bbf13 1022
00375592
VZ
1023 // look for the signature of the following record to decide which
1024 if ((u1 == LOCAL_MAGIC || u1 == CENTRAL_MAGIC) &&
1025 (u2 != LOCAL_MAGIC && u2 != CENTRAL_MAGIC))
1026 {
1027 // it's a pkzip style record after all!
1028 stream.Ungetch(buf, sizeof(buf));
1029 }
1030 else
1031 {
1032 // it's an info-zip record as expected
1033 stream.Ungetch(buf + 4, sizeof(buf) - 4);
26481315 1034 m_Crc = (wxUint32)m_CompressedSize;
00375592
VZ
1035 m_CompressedSize = m_Size;
1036 m_Size = u1;
1037 return SUMS_SIZE + 4;
1038 }
1039 }
1040
1041 return SUMS_SIZE;
1042}
1043
1044size_t wxZipEntry::WriteDescriptor(wxOutputStream& stream, wxUint32 crc,
1045 wxFileOffset compressedSize, wxFileOffset size)
1046{
1047 m_Crc = crc;
1048 m_CompressedSize = compressedSize;
1049 m_Size = size;
1050
1051 wxDataOutputStream ds(stream);
1052
1053 ds.Write32(crc);
26481315
WS
1054 ds.Write32((wxUint32)compressedSize);
1055 ds.Write32((wxUint32)size);
00375592
VZ
1056
1057 return SUMS_SIZE;
1058}
1059
1060
1061/////////////////////////////////////////////////////////////////////////////
1062// wxZipEndRec - holds the end of central directory record
1063
1064class wxZipEndRec
1065{
1066public:
1067 wxZipEndRec();
1068
1069 int GetDiskNumber() const { return m_DiskNumber; }
1070 int GetStartDisk() const { return m_StartDisk; }
1071 int GetEntriesHere() const { return m_EntriesHere; }
1072 int GetTotalEntries() const { return m_TotalEntries; }
1073 wxFileOffset GetSize() const { return m_Size; }
1074 wxFileOffset GetOffset() const { return m_Offset; }
1075 wxString GetComment() const { return m_Comment; }
1076
26481315
WS
1077 void SetDiskNumber(int num) { m_DiskNumber = (wxUint16)num; }
1078 void SetStartDisk(int num) { m_StartDisk = (wxUint16)num; }
1079 void SetEntriesHere(int num) { m_EntriesHere = (wxUint16)num; }
1080 void SetTotalEntries(int num) { m_TotalEntries = (wxUint16)num; }
00375592
VZ
1081 void SetSize(wxFileOffset size) { m_Size = (wxUint32)size; }
1082 void SetOffset(wxFileOffset offset) { m_Offset = (wxUint32)offset; }
1083 void SetComment(const wxString& comment) { m_Comment = comment; }
1084
1085 bool Read(wxInputStream& stream, wxMBConv& conv);
1086 bool Write(wxOutputStream& stream, wxMBConv& conv) const;
1087
1088private:
1089 wxUint16 m_DiskNumber;
1090 wxUint16 m_StartDisk;
1091 wxUint16 m_EntriesHere;
1092 wxUint16 m_TotalEntries;
1093 wxUint32 m_Size;
1094 wxUint32 m_Offset;
1095 wxString m_Comment;
1096};
1097
1098wxZipEndRec::wxZipEndRec()
1099 : m_DiskNumber(0),
1100 m_StartDisk(0),
1101 m_EntriesHere(0),
1102 m_TotalEntries(0),
1103 m_Size(0),
1104 m_Offset(0)
1105{
1106}
1107
1108bool wxZipEndRec::Write(wxOutputStream& stream, wxMBConv& conv) const
1109{
1110 const wxWX2MBbuf comment_buf = conv.cWX2MB(m_Comment);
1111 const char *comment = comment_buf;
1112 if (!comment) comment = "";
26481315 1113 wxUint16 commentLen = (wxUint16)strlen(comment);
00375592
VZ
1114
1115 wxDataOutputStream ds(stream);
1116
1117 ds << END_MAGIC << m_DiskNumber << m_StartDisk << m_EntriesHere
1118 << m_TotalEntries << m_Size << m_Offset << commentLen;
1119
1120 stream.Write(comment, commentLen);
1121
1122 return stream.IsOk();
1123}
1124
1125bool wxZipEndRec::Read(wxInputStream& stream, wxMBConv& conv)
1126{
1127 wxDataInputStream ds(stream);
1128 wxUint16 commentLen;
1129
1130 ds >> m_DiskNumber >> m_StartDisk >> m_EntriesHere
1131 >> m_TotalEntries >> m_Size >> m_Offset >> commentLen;
1132
1133 if (commentLen)
1134 m_Comment = ReadString(stream, commentLen, conv);
1135
1136 if (stream.IsOk())
1137 if (m_DiskNumber == 0 && m_StartDisk == 0 &&
1138 m_EntriesHere == m_TotalEntries)
1139 return true;
1140 else
1141 wxLogError(_("unsupported zip archive"));
1142
1143 return false;
1144}
1145
1146
1147/////////////////////////////////////////////////////////////////////////////
1148// A weak link from an input stream to an output stream
1149
1150class wxZipStreamLink
1151{
1152public:
1153 wxZipStreamLink(wxZipOutputStream *stream) : m_ref(1), m_stream(stream) { }
1154
1155 wxZipStreamLink *AddRef() { m_ref++; return this; }
1156 wxZipOutputStream *GetOutputStream() const { return m_stream; }
1157
1158 void Release(class wxZipInputStream *WXUNUSED(s))
1159 { if (--m_ref == 0) delete this; }
1160 void Release(class wxZipOutputStream *WXUNUSED(s))
1161 { m_stream = NULL; if (--m_ref == 0) delete this; }
1162
1163private:
f8fbc92b 1164 ~wxZipStreamLink() { }
00375592
VZ
1165
1166 int m_ref;
1167 wxZipOutputStream *m_stream;
1168};
1169
1170
1171/////////////////////////////////////////////////////////////////////////////
1172// Input stream
1173
1174wxDECLARE_SCOPED_PTR(wxZipEntry, _wxZipEntryPtr)
1175wxDEFINE_SCOPED_PTR (wxZipEntry, _wxZipEntryPtr)
1176
1177// constructor
1178//
1179wxZipInputStream::wxZipInputStream(wxInputStream& stream,
1180 wxMBConv& conv /*=wxConvLocal*/)
1181 : wxArchiveInputStream(stream, conv)
1182{
1183 m_ffile = NULL;
1184 Init();
1185}
1186
1187// Compatibility constructor
1188//
1189wxZipInputStream::wxZipInputStream(const wxString& archive,
1190 const wxString& file)
1191 : wxArchiveInputStream(OpenFile(archive), wxConvLocal)
1192{
1193 // no error messages
1194 wxLogNull nolog;
1195 Init();
1196 _wxZipEntryPtr entry;
1197
1198 if (m_ffile->Ok()) {
1199 do {
1200 entry.reset(GetNextEntry());
1201 }
1202 while (entry.get() != NULL && entry->GetInternalName() != file);
1203 }
1204
1205 if (entry.get() == NULL)
1206 m_lasterror = wxSTREAM_READ_ERROR;
1207}
1208
1209wxInputStream& wxZipInputStream::OpenFile(const wxString& archive)
1210{
1211 wxLogNull nolog;
1212 m_ffile = new wxFFileInputStream(archive);
1213 return *m_ffile;
1214}
1215
1216void wxZipInputStream::Init()
1217{
1218 m_store = new wxStoredInputStream(*m_parent_i_stream);
1219 m_inflate = NULL;
1220 m_rawin = NULL;
1221 m_raw = false;
1222 m_headerSize = 0;
1223 m_decomp = NULL;
1224 m_parentSeekable = false;
1225 m_weaklinks = new wxZipWeakLinks;
1226 m_streamlink = NULL;
1227 m_offsetAdjustment = 0;
1228 m_position = wxInvalidOffset;
1229 m_signature = 0;
1230 m_TotalEntries = 0;
1231 m_lasterror = m_parent_i_stream->GetLastError();
1232}
1233
1234wxZipInputStream::~wxZipInputStream()
1235{
1236 CloseDecompressor(m_decomp);
1237
1238 delete m_store;
1239 delete m_inflate;
1240 delete m_rawin;
1241 delete m_ffile;
1242
1243 m_weaklinks->Release(this);
ba9bbf13 1244
00375592
VZ
1245 if (m_streamlink)
1246 m_streamlink->Release(this);
1247}
1248
1249wxString wxZipInputStream::GetComment()
1250{
1251 if (m_position == wxInvalidOffset)
1252 if (!LoadEndRecord())
1253 return wxEmptyString;
1254
1255 if (!m_parentSeekable && Eof() && m_signature) {
1256 m_lasterror = wxSTREAM_NO_ERROR;
1257 m_lasterror = ReadLocal(true);
1258 }
1259
1260 return m_Comment;
1261}
1262
1263int wxZipInputStream::GetTotalEntries()
1264{
1265 if (m_position == wxInvalidOffset)
1266 LoadEndRecord();
1267 return m_TotalEntries;
1268}
1269
1270wxZipStreamLink *wxZipInputStream::MakeLink(wxZipOutputStream *out)
1271{
1272 wxZipStreamLink *link = NULL;
1273
1274 if (!m_parentSeekable && (IsOpened() || !Eof())) {
1275 link = new wxZipStreamLink(out);
1276 if (m_streamlink)
1277 m_streamlink->Release(this);
1278 m_streamlink = link->AddRef();
1279 }
1280
1281 return link;
1282}
d78b3d64 1283
00375592
VZ
1284bool wxZipInputStream::LoadEndRecord()
1285{
1286 wxCHECK(m_position == wxInvalidOffset, false);
1287 if (!IsOk())
1288 return false;
ea4f5235 1289
00375592
VZ
1290 m_position = 0;
1291
1292 // First find the end-of-central-directory record.
1293 if (!FindEndRecord()) {
1294 // failed, so either this is a non-seekable stream (ok), or not a zip
1295 if (m_parentSeekable) {
1296 m_lasterror = wxSTREAM_READ_ERROR;
1297 wxLogError(_("invalid zip file"));
1298 return false;
1299 }
1300 else {
1301 wxLogNull nolog;
1302 wxFileOffset pos = m_parent_i_stream->TellI();
1303 // FIXME
1304 //if (pos != wxInvalidOffset)
1305 if (pos >= 0 && pos <= LONG_MAX)
1306 m_offsetAdjustment = m_position = pos;
1307 return true;
1308 }
1309 }
1310
1311 wxZipEndRec endrec;
1312
1313 // Read in the end record
1314 wxFileOffset endPos = m_parent_i_stream->TellI() - 4;
1315 if (!endrec.Read(*m_parent_i_stream, GetConv())) {
1316 if (!*m_parent_i_stream) {
1317 m_lasterror = wxSTREAM_READ_ERROR;
1318 return false;
1319 }
1320 // TODO: try this out
1321 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1322 }
1323
1324 m_TotalEntries = endrec.GetTotalEntries();
1325 m_Comment = endrec.GetComment();
ea4f5235 1326
00375592 1327 // Now find the central-directory. we have the file offset of
ba9bbf13 1328 // the CD, so look there first.
00375592
VZ
1329 if (m_parent_i_stream->SeekI(endrec.GetOffset()) != wxInvalidOffset &&
1330 ReadSignature() == CENTRAL_MAGIC) {
1331 m_signature = CENTRAL_MAGIC;
1332 m_position = endrec.GetOffset();
1333 m_offsetAdjustment = 0;
1334 return true;
1335 }
ba9bbf13 1336
00375592
VZ
1337 // If it's not there, then it could be that the zip has been appended
1338 // to a self extractor, so take the CD size (also in endrec), subtract
1339 // it from the file offset of the end-central-directory and look there.
1340 if (m_parent_i_stream->SeekI(endPos - endrec.GetSize())
1341 != wxInvalidOffset && ReadSignature() == CENTRAL_MAGIC) {
1342 m_signature = CENTRAL_MAGIC;
1343 m_position = endPos - endrec.GetSize();
1344 m_offsetAdjustment = m_position - endrec.GetOffset();
1345 return true;
1346 }
1347
1348 wxLogError(_("can't find central directory in zip"));
1349 m_lasterror = wxSTREAM_READ_ERROR;
1350 return false;
1351}
5526e819 1352
00375592
VZ
1353// Find the end-of-central-directory record.
1354// If found the stream will be positioned just past the 4 signature bytes.
1355//
1356bool wxZipInputStream::FindEndRecord()
5526e819 1357{
3c70014d
MW
1358 if (!m_parent_i_stream->IsSeekable())
1359 return false;
1360
00375592 1361 // usually it's 22 bytes in size and the last thing in the file
ba9bbf13 1362 {
00375592
VZ
1363 wxLogNull nolog;
1364 if (m_parent_i_stream->SeekI(-END_SIZE, wxFromEnd) == wxInvalidOffset)
1365 return false;
1366 }
5526e819 1367
00375592
VZ
1368 m_parentSeekable = true;
1369 m_signature = 0;
1370 char magic[4];
1371 if (m_parent_i_stream->Read(magic, 4).LastRead() != 4)
1372 return false;
1373 if ((m_signature = CrackUint32(magic)) == END_MAGIC)
1374 return true;
1375
1376 // unfortunately, the record has a comment field that can be up to 65535
1377 // bytes in length, so if the signature not found then search backwards.
1378 wxFileOffset pos = m_parent_i_stream->TellI();
1379 const int BUFSIZE = 1024;
1380 wxCharBuffer buf(BUFSIZE);
1381
1382 memcpy(buf.data(), magic, 3);
1383 wxFileOffset minpos = wxMax(pos - 65535L, 0);
1384
1385 while (pos > minpos) {
26481315 1386 size_t len = (size_t)(pos - wxMax(pos - (BUFSIZE - 3), minpos));
00375592
VZ
1387 memcpy(buf.data() + len, buf, 3);
1388 pos -= len;
ba9bbf13 1389
00375592
VZ
1390 if (m_parent_i_stream->SeekI(pos, wxFromStart) == wxInvalidOffset ||
1391 m_parent_i_stream->Read(buf.data(), len).LastRead() != len)
1392 return false;
1393
1394 char *p = buf.data() + len;
1395
1396 while (p-- > buf.data()) {
1397 if ((m_signature = CrackUint32(p)) == END_MAGIC) {
1398 size_t remainder = buf.data() + len - p;
1399 if (remainder > 4)
1400 m_parent_i_stream->Ungetch(p + 4, remainder - 4);
1401 return true;
1402 }
1403 }
5526e819 1404 }
00375592
VZ
1405
1406 return false;
1407}
1408
1409wxZipEntry *wxZipInputStream::GetNextEntry()
1410{
1411 if (m_position == wxInvalidOffset)
1412 if (!LoadEndRecord())
1413 return NULL;
1414
1415 m_lasterror = m_parentSeekable ? ReadCentral() : ReadLocal();
1416 if (!IsOk())
1417 return NULL;
1418
1419 _wxZipEntryPtr entry(new wxZipEntry(m_entry));
1420 entry->m_backlink = m_weaklinks->AddEntry(entry.get(), entry->GetKey());
1421 return entry.release();
1422}
1423
1424wxStreamError wxZipInputStream::ReadCentral()
1425{
1426 if (!AtHeader())
1427 CloseEntry();
1428
1429 if (m_signature == END_MAGIC)
1430 return wxSTREAM_EOF;
1431
1432 if (m_signature != CENTRAL_MAGIC) {
1433 wxLogError(_("error reading zip central directory"));
1434 return wxSTREAM_READ_ERROR;
5526e819 1435 }
e90c1d2a 1436
00375592
VZ
1437 if (QuietSeek(*m_parent_i_stream, m_position + 4) == wxInvalidOffset)
1438 return wxSTREAM_READ_ERROR;
5526e819 1439
00375592
VZ
1440 m_position += m_entry.ReadCentral(*m_parent_i_stream, GetConv());
1441 if (m_parent_i_stream->GetLastError() == wxSTREAM_READ_ERROR) {
1442 m_signature = 0;
1443 return wxSTREAM_READ_ERROR;
5526e819 1444 }
00375592
VZ
1445
1446 m_signature = ReadSignature();
1447
1448 if (m_offsetAdjustment)
1449 m_entry.SetOffset(m_entry.GetOffset() + m_offsetAdjustment);
1450 m_entry.SetKey(m_entry.GetOffset());
1451
1452 return wxSTREAM_NO_ERROR;
5526e819
VS
1453}
1454
00375592
VZ
1455wxStreamError wxZipInputStream::ReadLocal(bool readEndRec /*=false*/)
1456{
1457 if (!AtHeader())
1458 CloseEntry();
1459
1460 if (!m_signature)
1461 m_signature = ReadSignature();
5526e819 1462
00375592
VZ
1463 if (m_signature == CENTRAL_MAGIC || m_signature == END_MAGIC) {
1464 if (m_streamlink && !m_streamlink->GetOutputStream()) {
1465 m_streamlink->Release(this);
1466 m_streamlink = NULL;
1467 }
1468 }
5526e819 1469
00375592
VZ
1470 while (m_signature == CENTRAL_MAGIC) {
1471 if (m_weaklinks->IsEmpty() && m_streamlink == NULL)
1472 return wxSTREAM_EOF;
ba9bbf13 1473
00375592
VZ
1474 m_position += m_entry.ReadCentral(*m_parent_i_stream, GetConv());
1475 m_signature = 0;
1476 if (m_parent_i_stream->GetLastError() == wxSTREAM_READ_ERROR)
1477 return wxSTREAM_READ_ERROR;
1478
1479 wxZipEntry *entry = m_weaklinks->GetEntry(m_entry.GetOffset());
1480 if (entry) {
1481 entry->SetSystemMadeBy(m_entry.GetSystemMadeBy());
1482 entry->SetVersionMadeBy(m_entry.GetVersionMadeBy());
1483 entry->SetComment(m_entry.GetComment());
1484 entry->SetDiskStart(m_entry.GetDiskStart());
1485 entry->SetInternalAttributes(m_entry.GetInternalAttributes());
1486 entry->SetExternalAttributes(m_entry.GetExternalAttributes());
1487 Copy(entry->m_Extra, m_entry.m_Extra);
1488 entry->Notify();
1489 m_weaklinks->RemoveEntry(entry->GetOffset());
1490 }
1491
1492 m_signature = ReadSignature();
1493 }
1494
1495 if (m_signature == END_MAGIC) {
1496 if (readEndRec || m_streamlink) {
1497 wxZipEndRec endrec;
1498 endrec.Read(*m_parent_i_stream, GetConv());
1499 m_Comment = endrec.GetComment();
1500 m_signature = 0;
1501 if (m_streamlink) {
1502 m_streamlink->GetOutputStream()->SetComment(endrec.GetComment());
1503 m_streamlink->Release(this);
1504 m_streamlink = NULL;
1505 }
1506 }
1507 return wxSTREAM_EOF;
1508 }
ba9bbf13 1509
00375592
VZ
1510 if (m_signature != LOCAL_MAGIC) {
1511 wxLogError(_("error reading zip local header"));
1512 return wxSTREAM_READ_ERROR;
1513 }
1514
1515 m_headerSize = m_entry.ReadLocal(*m_parent_i_stream, GetConv());
1516 m_signature = 0;
1517 m_entry.SetOffset(m_position);
1518 m_entry.SetKey(m_position);
1519
1520 if (m_parent_i_stream->GetLastError() == wxSTREAM_READ_ERROR) {
1521 return wxSTREAM_READ_ERROR;
1522 } else {
1523 m_TotalEntries++;
1524 return wxSTREAM_NO_ERROR;
1525 }
1526}
1527
1528wxUint32 wxZipInputStream::ReadSignature()
5526e819 1529{
00375592
VZ
1530 char magic[4];
1531 m_parent_i_stream->Read(magic, 4);
1532 return m_parent_i_stream->LastRead() == 4 ? CrackUint32(magic) : 0;
1533}
1534
1535bool wxZipInputStream::OpenEntry(wxArchiveEntry& entry)
1536{
1537 wxZipEntry *zipEntry = wxStaticCast(&entry, wxZipEntry);
1538 return zipEntry ? OpenEntry(*zipEntry) : false;
1539}
1540
1541// Open an entry
1542//
1543bool wxZipInputStream::DoOpen(wxZipEntry *entry, bool raw)
1544{
1545 if (m_position == wxInvalidOffset)
1546 if (!LoadEndRecord())
1547 return false;
1548 if (m_lasterror == wxSTREAM_READ_ERROR)
1549 return false;
1550 wxCHECK(!IsOpened(), false);
1551
1552 m_raw = raw;
1553
1554 if (entry) {
1555 if (AfterHeader() && entry->GetKey() == m_entry.GetOffset())
1556 return true;
1557 // can only open the current entry on a non-seekable stream
1558 wxCHECK(m_parentSeekable, false);
1559 }
ba9bbf13 1560
00375592 1561 m_lasterror = wxSTREAM_READ_ERROR;
ba9bbf13 1562
00375592
VZ
1563 if (entry)
1564 m_entry = *entry;
1565
1566 if (m_parentSeekable) {
1567 if (QuietSeek(*m_parent_i_stream, m_entry.GetOffset())
1568 == wxInvalidOffset)
1569 return false;
1570 if (ReadSignature() != LOCAL_MAGIC) {
1571 wxLogError(_("bad zipfile offset to entry"));
1572 return false;
1573 }
1574 }
1575
1576 if (m_parentSeekable || AtHeader()) {
1577 m_headerSize = m_entry.ReadLocal(*m_parent_i_stream, GetConv());
1578 if (m_parentSeekable) {
1579 wxZipEntry *ref = m_weaklinks->GetEntry(m_entry.GetKey());
1580 if (ref) {
1581 Copy(ref->m_LocalExtra, m_entry.m_LocalExtra);
1582 ref->Notify();
1583 m_weaklinks->RemoveEntry(ref->GetKey());
1584 }
1585 if (entry && entry != ref) {
1586 Copy(entry->m_LocalExtra, m_entry.m_LocalExtra);
1587 entry->Notify();
1588 }
1589 }
1590 }
1591
1592 m_lasterror = m_parent_i_stream->GetLastError();
1593 return IsOk();
1594}
1595
1596bool wxZipInputStream::OpenDecompressor(bool raw /*=false*/)
1597{
1598 wxASSERT(AfterHeader());
1599
1600 wxFileOffset compressedSize = m_entry.GetCompressedSize();
1601
1602 if (raw)
1603 m_raw = true;
1604
1605 if (m_raw) {
1606 if (compressedSize != wxInvalidOffset) {
1607 m_store->Open(compressedSize);
1608 m_decomp = m_store;
1609 } else {
1610 if (!m_rawin)
1611 m_rawin = new wxRawInputStream(*m_parent_i_stream);
1612 m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
1613 }
1614 } else {
1615 if (compressedSize != wxInvalidOffset &&
1616 (m_entry.GetMethod() != wxZIP_METHOD_DEFLATE ||
1617 wxZlibInputStream::CanHandleGZip())) {
1618 m_store->Open(compressedSize);
1619 m_decomp = OpenDecompressor(*m_store);
1620 } else {
1621 m_decomp = OpenDecompressor(*m_parent_i_stream);
1622 }
5526e819 1623 }
00375592
VZ
1624
1625 m_crcAccumulator = crc32(0, Z_NULL, 0);
1626 m_lasterror = m_decomp ? m_decomp->GetLastError() : wxSTREAM_READ_ERROR;
1627 return IsOk();
5526e819
VS
1628}
1629
00375592
VZ
1630// Can be overriden to add support for additional decompression methods
1631//
1632wxInputStream *wxZipInputStream::OpenDecompressor(wxInputStream& stream)
f6bcfd97 1633{
00375592
VZ
1634 switch (m_entry.GetMethod()) {
1635 case wxZIP_METHOD_STORE:
1636 if (m_entry.GetSize() == wxInvalidOffset) {
1637 wxLogError(_("stored file length not in Zip header"));
1638 break;
1639 }
1640 m_store->Open(m_entry.GetSize());
1641 return m_store;
1642
1643 case wxZIP_METHOD_DEFLATE:
1644 if (!m_inflate)
1645 m_inflate = new wxZlibInputStream2(stream);
1646 else
1647 m_inflate->Open(stream);
1648 return m_inflate;
f6bcfd97 1649
00375592
VZ
1650 default:
1651 wxLogError(_("unsupported Zip compression method"));
1652 }
1653
1654 return NULL;
f6bcfd97 1655}
5526e819 1656
00375592
VZ
1657bool wxZipInputStream::CloseDecompressor(wxInputStream *decomp)
1658{
1659 if (decomp && decomp == m_rawin)
1660 return CloseDecompressor(m_rawin->GetFilterInputStream());
1661 if (decomp != m_store && decomp != m_inflate)
1662 delete decomp;
1663 return true;
1664}
5526e819 1665
00375592
VZ
1666// Closes the current entry and positions the underlying stream at the start
1667// of the next entry
1668//
1669bool wxZipInputStream::CloseEntry()
5526e819 1670{
00375592
VZ
1671 if (AtHeader())
1672 return true;
1673 if (m_lasterror == wxSTREAM_READ_ERROR)
1674 return false;
f6bcfd97 1675
00375592
VZ
1676 if (!m_parentSeekable) {
1677 if (!IsOpened() && !OpenDecompressor(true))
1678 return false;
1679
1680 const int BUFSIZE = 8192;
1681 wxCharBuffer buf(BUFSIZE);
1682 while (IsOk())
1683 Read(buf.data(), BUFSIZE);
1684
1685 m_position += m_headerSize + m_entry.GetCompressedSize();
f6bcfd97
BP
1686 }
1687
00375592
VZ
1688 if (m_lasterror == wxSTREAM_EOF)
1689 m_lasterror = wxSTREAM_NO_ERROR;
f6bcfd97 1690
00375592
VZ
1691 CloseDecompressor(m_decomp);
1692 m_decomp = NULL;
1693 m_entry = wxZipEntry();
1694 m_headerSize = 0;
1695 m_raw = false;
f6bcfd97 1696
00375592 1697 return IsOk();
5526e819
VS
1698}
1699
00375592
VZ
1700size_t wxZipInputStream::OnSysRead(void *buffer, size_t size)
1701{
1702 if (!IsOpened())
1703 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1704 m_lasterror = wxSTREAM_READ_ERROR;
1705 if (!IsOk() || !size)
1706 return 0;
1707
1708 size_t count = m_decomp->Read(buffer, size).LastRead();
1709 if (!m_raw)
1710 m_crcAccumulator = crc32(m_crcAccumulator, (Byte*)buffer, count);
1711 m_lasterror = m_decomp->GetLastError();
1712
1713 if (Eof()) {
1714 if ((m_entry.GetFlags() & wxZIP_SUMS_FOLLOW) != 0) {
1715 m_headerSize += m_entry.ReadDescriptor(*m_parent_i_stream);
1716 wxZipEntry *entry = m_weaklinks->GetEntry(m_entry.GetKey());
1717
1718 if (entry) {
1719 entry->SetCrc(m_entry.GetCrc());
1720 entry->SetCompressedSize(m_entry.GetCompressedSize());
1721 entry->SetSize(m_entry.GetSize());
1722 entry->Notify();
1723 }
1724 }
1725
1726 if (!m_raw) {
1727 m_lasterror = wxSTREAM_READ_ERROR;
1728
1729 if (m_parent_i_stream->IsOk()) {
1730 if (m_entry.GetSize() != TellI())
1731 wxLogError(_("reading zip stream (entry %s): bad length"),
1732 m_entry.GetName().c_str());
1733 else if (m_crcAccumulator != m_entry.GetCrc())
1734 wxLogError(_("reading zip stream (entry %s): bad crc"),
1735 m_entry.GetName().c_str());
1736 else
1737 m_lasterror = wxSTREAM_EOF;
1738 }
1739 }
1740 }
5526e819 1741
00375592
VZ
1742 return count;
1743}
5526e819 1744
00375592
VZ
1745// Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1746//
4004775e 1747wxFileOffset wxZipInputStream::OnSysSeek(wxFileOffset seek, wxSeekMode mode)
5526e819 1748{
00375592
VZ
1749 if (!m_ffile || AtHeader())
1750 return wxInvalidOffset;
1751
cab1a605 1752 // NB: since ZIP files don't natively support seeking, we have to
03c0fc66 1753 // implement a brute force workaround -- reading all the data
cab1a605 1754 // between current and the new position (or between beginning of
03c0fc66
VS
1755 // the file and new position...)
1756
4004775e 1757 wxFileOffset nextpos;
00375592 1758 wxFileOffset pos = TellI();
5526e819 1759
03c0fc66 1760 switch ( mode )
d1af991f 1761 {
00375592 1762 case wxFromCurrent : nextpos = seek + pos; break;
5526e819 1763 case wxFromStart : nextpos = seek; break;
46263455 1764 case wxFromEnd : nextpos = GetLength() - 1 + seek; break;
00375592 1765 default : nextpos = pos; break; /* just to fool compiler, never happens */
5526e819
VS
1766 }
1767
ba9bbf13 1768 size_t toskip wxDUMMY_INITIALIZE(0);
00375592 1769 if ( nextpos >= pos )
d1af991f 1770 {
26481315 1771 toskip = (size_t)(nextpos - pos);
5526e819 1772 }
03c0fc66
VS
1773 else
1774 {
00375592
VZ
1775 wxZipEntry current(m_entry);
1776 CloseEntry();
1777 if (!OpenEntry(current))
e90c1d2a 1778 {
2b5f62a0 1779 m_lasterror = wxSTREAM_READ_ERROR;
00375592 1780 return pos;
5526e819 1781 }
26481315 1782 toskip = (size_t)nextpos;
03c0fc66 1783 }
cab1a605 1784
03c0fc66
VS
1785 if ( toskip > 0 )
1786 {
1787 const size_t BUFSIZE = 4096;
1788 size_t sz;
1789 char buffer[BUFSIZE];
1790 while ( toskip > 0 )
1791 {
1792 sz = wxMin(toskip, BUFSIZE);
00375592 1793 Read(buffer, sz);
03c0fc66
VS
1794 toskip -= sz;
1795 }
5526e819
VS
1796 }
1797
00375592
VZ
1798 pos = nextpos;
1799 return pos;
5526e819
VS
1800}
1801
00375592
VZ
1802
1803/////////////////////////////////////////////////////////////////////////////
1804// Output stream
1805
28997d37 1806#include "wx/listimpl.cpp"
00375592
VZ
1807WX_DEFINE_LIST(_wxZipEntryList);
1808
1809wxZipOutputStream::wxZipOutputStream(wxOutputStream& stream,
1810 int level /*=-1*/,
1811 wxMBConv& conv /*=wxConvLocal*/)
1812 : wxArchiveOutputStream(stream, conv),
1813 m_store(new wxStoredOutputStream(stream)),
1814 m_deflate(NULL),
1815 m_backlink(NULL),
1816 m_initialData(new char[OUTPUT_LATENCY]),
1817 m_initialSize(0),
1818 m_pending(NULL),
1819 m_raw(false),
1820 m_headerOffset(0),
1821 m_headerSize(0),
1822 m_entrySize(0),
1823 m_comp(NULL),
1824 m_level(level),
1825 m_offsetAdjustment(wxInvalidOffset)
1826{
1827}
ba9bbf13 1828
00375592
VZ
1829wxZipOutputStream::~wxZipOutputStream()
1830{
1831 Close();
1832 WX_CLEAR_LIST(_wxZipEntryList, m_entries);
1833 delete m_store;
1834 delete m_deflate;
1835 delete m_pending;
1836 delete [] m_initialData;
1837 if (m_backlink)
1838 m_backlink->Release(this);
1839}
1840
1841bool wxZipOutputStream::PutNextEntry(
1842 const wxString& name,
1843 const wxDateTime& dt /*=wxDateTime::Now()*/,
1844 wxFileOffset size /*=wxInvalidOffset*/)
1845{
1846 return PutNextEntry(new wxZipEntry(name, dt, size));
1847}
1848
1849bool wxZipOutputStream::PutNextDirEntry(
1850 const wxString& name,
1851 const wxDateTime& dt /*=wxDateTime::Now()*/)
1852{
1853 wxZipEntry *entry = new wxZipEntry(name, dt);
1854 entry->SetIsDir();
1855 return PutNextEntry(entry);
1856}
1857
1858bool wxZipOutputStream::CopyEntry(wxZipEntry *entry,
1859 wxZipInputStream& inputStream)
1860{
1861 _wxZipEntryPtr e(entry);
1862
1863 return
1864 inputStream.DoOpen(e.get(), true) &&
1865 DoCreate(e.release(), true) &&
1866 Write(inputStream).IsOk() && inputStream.Eof();
1867}
1868
1869bool wxZipOutputStream::PutNextEntry(wxArchiveEntry *entry)
1870{
1871 wxZipEntry *zipEntry = wxStaticCast(entry, wxZipEntry);
1872 if (!zipEntry)
1873 delete entry;
1874 return PutNextEntry(zipEntry);
1875}
1876
1877bool wxZipOutputStream::CopyEntry(wxArchiveEntry *entry,
1878 wxArchiveInputStream& stream)
1879{
1880 wxZipEntry *zipEntry = wxStaticCast(entry, wxZipEntry);
1881
1882 if (!zipEntry || !stream.OpenEntry(*zipEntry)) {
1883 delete entry;
1884 return false;
1885 }
1886
1887 return CopyEntry(zipEntry, wx_static_cast(wxZipInputStream&, stream));
1888}
1889
1890bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream& inputStream)
1891{
1892 m_Comment = inputStream.GetComment();
1893 if (m_backlink)
1894 m_backlink->Release(this);
1895 m_backlink = inputStream.MakeLink(this);
1896 return true;
1897}
1898
1899bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream& stream)
1900{
1901 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream&, stream));
1902}
1903
1904void wxZipOutputStream::SetLevel(int level)
1905{
1906 if (level != m_level) {
1907 if (m_comp != m_deflate)
1908 delete m_deflate;
1909 m_deflate = NULL;
1910 m_level = level;
1911 }
1912}
1913
1914bool wxZipOutputStream::DoCreate(wxZipEntry *entry, bool raw /*=false*/)
1915{
1916 CloseEntry();
1917
1918 m_pending = entry;
1919 if (!m_pending)
1920 return false;
1921
1922 // write the signature bytes right away
1923 wxDataOutputStream ds(*m_parent_o_stream);
1924 ds << LOCAL_MAGIC;
1925
1926 // and if this is the first entry test for seekability
3c70014d 1927 if (m_headerOffset == 0 && m_parent_o_stream->IsSeekable()) {
00375592
VZ
1928 bool logging = wxLog::IsEnabled();
1929 wxLogNull nolog;
1930 wxFileOffset here = m_parent_o_stream->TellO();
1931
1932 if (here != wxInvalidOffset && here >= 4) {
1933 if (m_parent_o_stream->SeekO(here - 4) == here - 4) {
1934 m_offsetAdjustment = here - 4;
1935 wxLog::EnableLogging(logging);
1936 m_parent_o_stream->SeekO(here);
1937 }
1938 }
1939 }
1940
1941 m_pending->SetOffset(m_headerOffset);
1942
1943 m_crcAccumulator = crc32(0, Z_NULL, 0);
1944
1945 if (raw)
1946 m_raw = true;
1947
1948 m_lasterror = wxSTREAM_NO_ERROR;
1949 return true;
1950}
1951
1952// Can be overriden to add support for additional compression methods
1953//
1954wxOutputStream *wxZipOutputStream::OpenCompressor(
1955 wxOutputStream& stream,
1956 wxZipEntry& entry,
1957 const Buffer bufs[])
1958{
1959 if (entry.GetMethod() == wxZIP_METHOD_DEFAULT) {
1960 if (GetLevel() == 0
1961 && (IsParentSeekable()
1962 || entry.GetCompressedSize() != wxInvalidOffset
1963 || entry.GetSize() != wxInvalidOffset)) {
1964 entry.SetMethod(wxZIP_METHOD_STORE);
1965 } else {
1966 int size = 0;
1967 for (int i = 0; bufs[i].m_data; ++i)
1968 size += bufs[i].m_size;
1969 entry.SetMethod(size <= 6 ?
1970 wxZIP_METHOD_STORE : wxZIP_METHOD_DEFLATE);
1971 }
1972 }
1973
1974 switch (entry.GetMethod()) {
1975 case wxZIP_METHOD_STORE:
1976 if (entry.GetCompressedSize() == wxInvalidOffset)
1977 entry.SetCompressedSize(entry.GetSize());
1978 return m_store;
1979
1980 case wxZIP_METHOD_DEFLATE:
1981 {
1982 int defbits = wxZIP_DEFLATE_NORMAL;
1983 switch (GetLevel()) {
1984 case 0: case 1:
1985 defbits = wxZIP_DEFLATE_SUPERFAST;
1986 break;
1987 case 2: case 3: case 4:
1988 defbits = wxZIP_DEFLATE_FAST;
1989 break;
1990 case 8: case 9:
1991 defbits = wxZIP_DEFLATE_EXTRA;
1992 break;
1993 }
1994 entry.SetFlags((entry.GetFlags() & ~wxZIP_DEFLATE_MASK) |
1995 defbits | wxZIP_SUMS_FOLLOW);
1996
1997 if (!m_deflate)
1998 m_deflate = new wxZlibOutputStream2(stream, GetLevel());
1999 else
2000 m_deflate->Open(stream);
2001
2002 return m_deflate;
2003 }
2004
2005 default:
2006 wxLogError(_("unsupported Zip compression method"));
2007 }
2008
2009 return NULL;
2010}
2011
2012bool wxZipOutputStream::CloseCompressor(wxOutputStream *comp)
2013{
2014 if (comp == m_deflate)
2015 m_deflate->Close();
2016 else if (comp != m_store)
2017 delete comp;
2018 return true;
2019}
2020
2021// This is called when OUPUT_LATENCY bytes has been written to the
2022// wxZipOutputStream to actually create the zip entry.
2023//
2024void wxZipOutputStream::CreatePendingEntry(const void *buffer, size_t size)
2025{
2026 wxASSERT(IsOk() && m_pending && !m_comp);
2027 _wxZipEntryPtr spPending(m_pending);
2028 m_pending = NULL;
2029
2030 Buffer bufs[] = {
2031 { m_initialData, m_initialSize },
2032 { (const char*)buffer, size },
2033 { NULL, 0 }
2034 };
2035
2036 if (m_raw)
2037 m_comp = m_store;
2038 else
2039 m_comp = OpenCompressor(*m_store, *spPending,
2040 m_initialSize ? bufs : bufs + 1);
2041
2042 if (IsParentSeekable()
2043 || (spPending->m_Crc
2044 && spPending->m_CompressedSize != wxInvalidOffset
2045 && spPending->m_Size != wxInvalidOffset))
2046 spPending->m_Flags &= ~wxZIP_SUMS_FOLLOW;
2047 else
2048 if (spPending->m_CompressedSize != wxInvalidOffset)
2049 spPending->m_Flags |= wxZIP_SUMS_FOLLOW;
2050
2051 m_headerSize = spPending->WriteLocal(*m_parent_o_stream, GetConv());
2052 m_lasterror = m_parent_o_stream->GetLastError();
2053
2054 if (IsOk()) {
2055 m_entries.push_back(spPending.release());
2056 OnSysWrite(m_initialData, m_initialSize);
2057 }
2058
2059 m_initialSize = 0;
2060}
2061
2062// This is called to write out the zip entry when Close has been called
2063// before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2064//
2065void wxZipOutputStream::CreatePendingEntry()
2066{
2067 wxASSERT(IsOk() && m_pending && !m_comp);
2068 _wxZipEntryPtr spPending(m_pending);
2069 m_pending = NULL;
2070 m_lasterror = wxSTREAM_WRITE_ERROR;
2071
2072 if (!m_raw) {
2073 // Initially compresses the data to memory, then fall back to 'store'
2074 // if the compressor makes the data larger rather than smaller.
2075 wxMemoryOutputStream mem;
2076 Buffer bufs[] = { { m_initialData, m_initialSize }, { NULL, 0 } };
2077 wxOutputStream *comp = OpenCompressor(mem, *spPending, bufs);
2078
2079 if (!comp)
2080 return;
2081 if (comp != m_store) {
2082 bool ok = comp->Write(m_initialData, m_initialSize).IsOk();
2083 CloseCompressor(comp);
2084 if (!ok)
2085 return;
2086 }
2087
2088 m_entrySize = m_initialSize;
2089 m_crcAccumulator = crc32(0, (Byte*)m_initialData, m_initialSize);
2090
2091 if (mem.GetSize() > 0 && mem.GetSize() < m_initialSize) {
2092 m_initialSize = mem.GetSize();
2093 mem.CopyTo(m_initialData, m_initialSize);
2094 } else {
2095 spPending->SetMethod(wxZIP_METHOD_STORE);
2096 }
2097
2098 spPending->SetSize(m_entrySize);
2099 spPending->SetCrc(m_crcAccumulator);
2100 spPending->SetCompressedSize(m_initialSize);
2101 }
2102
2103 spPending->m_Flags &= ~wxZIP_SUMS_FOLLOW;
2104 m_headerSize = spPending->WriteLocal(*m_parent_o_stream, GetConv());
2105
2106 if (m_parent_o_stream->IsOk()) {
2107 m_entries.push_back(spPending.release());
2108 m_comp = m_store;
2109 m_store->Write(m_initialData, m_initialSize);
2110 }
2111
2112 m_initialSize = 0;
2113 m_lasterror = m_parent_o_stream->GetLastError();
2114}
2115
2116// Write the 'central directory' and the 'end-central-directory' records.
2117//
2118bool wxZipOutputStream::Close()
2119{
2120 CloseEntry();
2121
2122 if (m_lasterror == wxSTREAM_WRITE_ERROR || m_entries.size() == 0)
2123 return false;
2124
2125 wxZipEndRec endrec;
2126
2127 endrec.SetEntriesHere(m_entries.size());
2128 endrec.SetTotalEntries(m_entries.size());
2129 endrec.SetOffset(m_headerOffset);
2130 endrec.SetComment(m_Comment);
2131
2132 _wxZipEntryList::iterator it;
2133 wxFileOffset size = 0;
2134
2135 for (it = m_entries.begin(); it != m_entries.end(); ++it) {
2136 size += (*it)->WriteCentral(*m_parent_o_stream, GetConv());
2137 delete *it;
2138 }
2139 m_entries.clear();
2140
2141 endrec.SetSize(size);
2142 endrec.Write(*m_parent_o_stream, GetConv());
2143
2144 m_lasterror = m_parent_o_stream->GetLastError();
2145 if (!IsOk())
2146 return false;
2147 m_lasterror = wxSTREAM_EOF;
2148 return true;
2149}
2150
2151// Finish writing the current entry
2152//
2153bool wxZipOutputStream::CloseEntry()
2154{
2155 if (IsOk() && m_pending)
2156 CreatePendingEntry();
2157 if (!IsOk())
2158 return false;
2159 if (!m_comp)
2160 return true;
2161
2162 CloseCompressor(m_comp);
2163 m_comp = NULL;
2164
2165 wxFileOffset compressedSize = m_store->TellO();
2166
2167 wxZipEntry& entry = *m_entries.back();
2168
2169 // When writing raw the crc and size can't be checked
2170 if (m_raw) {
2171 m_crcAccumulator = entry.GetCrc();
2172 m_entrySize = entry.GetSize();
2173 }
2174
2175 // Write the sums in the trailing 'data descriptor' if necessary
2176 if (entry.m_Flags & wxZIP_SUMS_FOLLOW) {
2177 wxASSERT(!IsParentSeekable());
2178 m_headerOffset +=
2179 entry.WriteDescriptor(*m_parent_o_stream, m_crcAccumulator,
2180 compressedSize, m_entrySize);
2181 m_lasterror = m_parent_o_stream->GetLastError();
2182 }
2183
2184 // If the local header didn't have the correct crc and size written to
2185 // it then seek back and fix it
2186 else if (m_crcAccumulator != entry.GetCrc()
2187 || m_entrySize != entry.GetSize()
2188 || compressedSize != entry.GetCompressedSize())
2189 {
2190 if (IsParentSeekable()) {
2191 wxFileOffset here = m_parent_o_stream->TellO();
2192 wxFileOffset headerOffset = m_headerOffset + m_offsetAdjustment;
2193 m_parent_o_stream->SeekO(headerOffset + SUMS_OFFSET);
2194 entry.WriteDescriptor(*m_parent_o_stream, m_crcAccumulator,
2195 compressedSize, m_entrySize);
2196 m_parent_o_stream->SeekO(here);
2197 m_lasterror = m_parent_o_stream->GetLastError();
2198 } else {
2199 m_lasterror = wxSTREAM_WRITE_ERROR;
2200 }
2201 }
2202
2203 m_headerOffset += m_headerSize + compressedSize;
26481315
WS
2204 m_headerSize = 0;
2205 m_entrySize = 0;
00375592
VZ
2206 m_store->Close();
2207 m_raw = false;
2208
2209 if (IsOk())
2210 m_lasterror = m_parent_o_stream->GetLastError();
2211 else
2212 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2213 entry.GetName().c_str());
2214 return IsOk();
2215}
2216
2217void wxZipOutputStream::Sync()
2218{
2219 if (IsOk() && m_pending)
2220 CreatePendingEntry(NULL, 0);
2221 if (!m_comp)
2222 m_lasterror = wxSTREAM_WRITE_ERROR;
2223 if (IsOk()) {
2224 m_comp->Sync();
2225 m_lasterror = m_comp->GetLastError();
2226 }
2227}
2228
2229size_t wxZipOutputStream::OnSysWrite(const void *buffer, size_t size)
2230{
2231 if (IsOk() && m_pending) {
2232 if (m_initialSize + size < OUTPUT_LATENCY) {
2233 memcpy(m_initialData + m_initialSize, buffer, size);
2234 m_initialSize += size;
2235 return size;
2236 } else {
2237 CreatePendingEntry(buffer, size);
2238 }
2239 }
2240
2241 if (!m_comp)
2242 m_lasterror = wxSTREAM_WRITE_ERROR;
2243 if (!IsOk() || !size)
2244 return 0;
2245
2246 if (m_comp->Write(buffer, size).LastWrite() != size)
2247 m_lasterror = wxSTREAM_WRITE_ERROR;
2248 m_crcAccumulator = crc32(m_crcAccumulator, (Byte*)buffer, size);
2249 m_entrySize += m_comp->LastWrite();
2250
2251 return m_comp->LastWrite();
2252}
2253
2254#endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM