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