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