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