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