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