hook the docview-specific customization of event handling logic at TryValidator(...
[wxWidgets.git] / src / common / tarstrm.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: tarstrm.cpp
3 // Purpose: Streams for Tar files
4 // Author: Mike Wetherell
5 // RCS-ID: $Id$
6 // Copyright: (c) 2004 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 #if wxUSE_TARSTREAM
18
19 #include "wx/tarstrm.h"
20
21 #ifndef WX_PRECOMP
22 #include "wx/intl.h"
23 #include "wx/log.h"
24 #include "wx/utils.h"
25 #endif
26
27 #include "wx/buffer.h"
28 #include "wx/datetime.h"
29 #include "wx/ptr_scpd.h"
30 #include "wx/filename.h"
31 #include "wx/thread.h"
32
33 #include <ctype.h>
34
35 #ifdef __UNIX__
36 #include <pwd.h>
37 #include <grp.h>
38 #endif
39
40
41 /////////////////////////////////////////////////////////////////////////////
42 // constants
43
44 enum {
45 TAR_NAME,
46 TAR_MODE,
47 TAR_UID,
48 TAR_GID,
49 TAR_SIZE,
50 TAR_MTIME,
51 TAR_CHKSUM,
52 TAR_TYPEFLAG,
53 TAR_LINKNAME,
54 TAR_MAGIC,
55 TAR_VERSION,
56 TAR_UNAME,
57 TAR_GNAME,
58 TAR_DEVMAJOR,
59 TAR_DEVMINOR,
60 TAR_PREFIX,
61 TAR_UNUSED,
62 TAR_NUMFIELDS
63 };
64
65 enum {
66 TAR_BLOCKSIZE = 512
67 };
68
69 // checksum type
70 enum {
71 SUM_UNKNOWN,
72 SUM_UNSIGNED,
73 SUM_SIGNED
74 };
75
76 // type of input tar
77 enum {
78 TYPE_OLDTAR, // fields after TAR_LINKNAME are invalid
79 TYPE_GNUTAR, // all fields except TAR_PREFIX are valid
80 TYPE_USTAR // all fields are valid
81 };
82
83 // signatures
84 static const char *USTAR_MAGIC = "ustar";
85 static const char *USTAR_VERSION = "00";
86 static const char *GNU_MAGIC = "ustar ";
87 static const char *GNU_VERION = " ";
88
89 IMPLEMENT_DYNAMIC_CLASS(wxTarEntry, wxArchiveEntry)
90 IMPLEMENT_DYNAMIC_CLASS(wxTarClassFactory, wxArchiveClassFactory)
91
92
93 /////////////////////////////////////////////////////////////////////////////
94 // Class factory
95
96 static wxTarClassFactory g_wxTarClassFactory;
97
98 wxTarClassFactory::wxTarClassFactory()
99 {
100 if (this == &g_wxTarClassFactory)
101 PushFront();
102 }
103
104 const wxChar * const *
105 wxTarClassFactory::GetProtocols(wxStreamProtocolType type) const
106 {
107 static const wxChar *protocols[] = { _T("tar"), NULL };
108 static const wxChar *mimetypes[] = { _T("application/x-tar"), NULL };
109 static const wxChar *fileexts[] = { _T(".tar"), NULL };
110 static const wxChar *empty[] = { NULL };
111
112 switch (type) {
113 case wxSTREAM_PROTOCOL: return protocols;
114 case wxSTREAM_MIMETYPE: return mimetypes;
115 case wxSTREAM_FILEEXT: return fileexts;
116 default: return empty;
117 }
118 }
119
120
121 /////////////////////////////////////////////////////////////////////////////
122 // tar header block
123
124 typedef wxFileOffset wxTarNumber;
125
126 struct wxTarField { const wxChar *name; int pos; };
127
128 class wxTarHeaderBlock
129 {
130 public:
131 wxTarHeaderBlock()
132 { memset(data, 0, sizeof(data)); }
133 wxTarHeaderBlock(const wxTarHeaderBlock& hb)
134 { memcpy(data, hb.data, sizeof(data)); }
135
136 bool Read(wxInputStream& in);
137 bool Write(wxOutputStream& out);
138 inline bool WriteField(wxOutputStream& out, int id);
139
140 bool IsAllZeros() const;
141 wxUint32 Sum(bool SignedSum = false);
142 wxUint32 SumField(int id);
143
144 char *Get(int id) { return data + fields[id].pos + id; }
145 static size_t Len(int id) { return fields[id + 1].pos - fields[id].pos; }
146 static const wxChar *Name(int id) { return fields[id].name; }
147 static size_t Offset(int id) { return fields[id].pos; }
148
149 bool SetOctal(int id, wxTarNumber n);
150 wxTarNumber GetOctal(int id);
151 bool SetPath(const wxString& name, wxMBConv& conv);
152
153 private:
154 char data[TAR_BLOCKSIZE + TAR_NUMFIELDS];
155 static const wxTarField fields[];
156 static void check();
157 };
158
159 wxDEFINE_SCOPED_PTR_TYPE(wxTarHeaderBlock)
160
161 // A table giving the field names and offsets in a tar header block
162 const wxTarField wxTarHeaderBlock::fields[] =
163 {
164 { _T("name"), 0 }, // 100
165 { _T("mode"), 100 }, // 8
166 { _T("uid"), 108 }, // 8
167 { _T("gid"), 116 }, // 8
168 { _T("size"), 124 }, // 12
169 { _T("mtime"), 136 }, // 12
170 { _T("chksum"), 148 }, // 8
171 { _T("typeflag"), 156 }, // 1
172 { _T("linkname"), 157 }, // 100
173 { _T("magic"), 257 }, // 6
174 { _T("version"), 263 }, // 2
175 { _T("uname"), 265 }, // 32
176 { _T("gname"), 297 }, // 32
177 { _T("devmajor"), 329 }, // 8
178 { _T("devminor"), 337 }, // 8
179 { _T("prefix"), 345 }, // 155
180 { _T("unused"), 500 }, // 12
181 { NULL, TAR_BLOCKSIZE }
182 };
183
184 void wxTarHeaderBlock::check()
185 {
186 #if 0
187 wxCOMPILE_TIME_ASSERT(
188 WXSIZEOF(fields) == TAR_NUMFIELDS + 1,
189 Wrong_number_of_elements_in_fields_table
190 );
191 #endif
192 }
193
194 bool wxTarHeaderBlock::IsAllZeros() const
195 {
196 const char *p = data;
197 for (size_t i = 0; i < sizeof(data); i++)
198 if (p[i])
199 return false;
200 return true;
201 }
202
203 wxUint32 wxTarHeaderBlock::Sum(bool SignedSum /*=false*/)
204 {
205 // the chksum field itself should be blanks during the calculation
206 memset(Get(TAR_CHKSUM), ' ', Len(TAR_CHKSUM));
207 const char *p = data;
208 wxUint32 n = 0;
209
210 if (SignedSum)
211 for (size_t i = 0; i < sizeof(data); i++)
212 n += (signed char)p[i];
213 else
214 for (size_t i = 0; i < sizeof(data); i++)
215 n += (unsigned char)p[i];
216
217 return n;
218 }
219
220 wxUint32 wxTarHeaderBlock::SumField(int id)
221 {
222 unsigned char *p = (unsigned char*)Get(id);
223 unsigned char *q = p + Len(id);
224 wxUint32 n = 0;
225
226 while (p < q)
227 n += *p++;
228
229 return n;
230 }
231
232 bool wxTarHeaderBlock::Read(wxInputStream& in)
233 {
234 bool ok = true;
235
236 for (int id = 0; id < TAR_NUMFIELDS && ok; id++)
237 ok = in.Read(Get(id), Len(id)).LastRead() == Len(id);
238
239 return ok;
240 }
241
242 bool wxTarHeaderBlock::Write(wxOutputStream& out)
243 {
244 bool ok = true;
245
246 for (int id = 0; id < TAR_NUMFIELDS && ok; id++)
247 ok = WriteField(out, id);
248
249 return ok;
250 }
251
252 inline bool wxTarHeaderBlock::WriteField(wxOutputStream& out, int id)
253 {
254 return out.Write(Get(id), Len(id)).LastWrite() == Len(id);
255 }
256
257 wxTarNumber wxTarHeaderBlock::GetOctal(int id)
258 {
259 wxTarNumber n = 0;
260 const char *p = Get(id);
261 while (*p == ' ')
262 p++;
263 while (*p >= '0' && *p < '8')
264 n = (n << 3) | (*p++ - '0');
265 return n;
266 }
267
268 bool wxTarHeaderBlock::SetOctal(int id, wxTarNumber n)
269 {
270 // set an octal field, return true if the number fits
271 char *field = Get(id);
272 char *p = field + Len(id);
273 *--p = 0;
274 while (p > field) {
275 *--p = char('0' + (n & 7));
276 n >>= 3;
277 }
278 return n == 0;
279 }
280
281 bool wxTarHeaderBlock::SetPath(const wxString& name, wxMBConv& conv)
282 {
283 bool badconv = false;
284
285 #if wxUSE_UNICODE
286 wxCharBuffer nameBuf = name.mb_str(conv);
287
288 // if the conversion fails make an approximation
289 if (!nameBuf) {
290 badconv = true;
291 size_t len = name.length();
292 wxCharBuffer approx(len);
293 for (size_t i = 0; i < len; i++)
294 {
295 wxChar c = name[i];
296 approx.data()[i] = c & ~0x7F ? '_' : c;
297 }
298 nameBuf = approx;
299 }
300
301 const char *mbName = nameBuf;
302 #else
303 const char *mbName = name.c_str();
304 (void)conv;
305 #endif
306
307 bool fits;
308 bool notGoingToFit = false;
309 size_t len = strlen(mbName);
310 size_t maxname = Len(TAR_NAME);
311 size_t maxprefix = Len(TAR_PREFIX);
312 size_t i = 0;
313 size_t nexti = 0;
314
315 for (;;) {
316 fits = i < maxprefix && len - i <= maxname;
317
318 if (!fits) {
319 const char *p = strchr(mbName + i, '/');
320 if (p)
321 nexti = p - mbName + 1;
322 if (!p || nexti - 1 > maxprefix)
323 notGoingToFit = true;
324 }
325
326 if (fits || notGoingToFit) {
327 strncpy(Get(TAR_NAME), mbName + i, maxname);
328 if (i > 0)
329 strncpy(Get(TAR_PREFIX), mbName, i - 1);
330 break;
331 }
332
333 i = nexti;
334 }
335
336 return fits && !badconv;
337 }
338
339
340 /////////////////////////////////////////////////////////////////////////////
341 // Some helpers
342
343 static wxFileOffset RoundUpSize(wxFileOffset size, int factor = 1)
344 {
345 wxFileOffset chunk = TAR_BLOCKSIZE * factor;
346 return ((size + chunk - 1) / chunk) * chunk;
347 }
348
349 #ifdef __UNIX__
350
351 static wxString wxTarUserName(int uid)
352 {
353 struct passwd *ppw;
354
355 #ifdef HAVE_GETPWUID_R
356 #if defined HAVE_SYSCONF && defined _SC_GETPW_R_SIZE_MAX
357 long pwsize = sysconf(_SC_GETPW_R_SIZE_MAX);
358 size_t bufsize(wxMin(wxMax(1024l, pwsize), 32768l));
359 #else
360 size_t bufsize = 1024;
361 #endif
362 wxCharBuffer buf(bufsize);
363 struct passwd pw;
364
365 memset(&pw, 0, sizeof(pw));
366 if (getpwuid_r(uid, &pw, buf.data(), bufsize, &ppw) == 0 && pw.pw_name)
367 return wxString(pw.pw_name, wxConvLibc);
368 #else
369 if ((ppw = getpwuid(uid)) != NULL)
370 return wxString(ppw->pw_name, wxConvLibc);
371 #endif
372 return _("unknown");
373 }
374
375 static wxString wxTarGroupName(int gid)
376 {
377 struct group *pgr;
378 #ifdef HAVE_GETGRGID_R
379 #if defined HAVE_SYSCONF && defined _SC_GETGR_R_SIZE_MAX
380 long grsize = sysconf(_SC_GETGR_R_SIZE_MAX);
381 size_t bufsize(wxMin(wxMax(1024l, grsize), 32768l));
382 #else
383 size_t bufsize = 1024;
384 #endif
385 wxCharBuffer buf(bufsize);
386 struct group gr;
387
388 memset(&gr, 0, sizeof(gr));
389 if (getgrgid_r(gid, &gr, buf.data(), bufsize, &pgr) == 0 && gr.gr_name)
390 return wxString(gr.gr_name, wxConvLibc);
391 #else
392 if ((pgr = getgrgid(gid)) != NULL)
393 return wxString(pgr->gr_name, wxConvLibc);
394 #endif
395 return _("unknown");
396 }
397
398 #endif // __UNIX__
399
400 // Cache the user and group names since getting them can be expensive,
401 // get both names and ids at the same time.
402 //
403 struct wxTarUser
404 {
405 wxTarUser();
406 ~wxTarUser() { delete [] uname; delete [] gname; }
407
408 int uid;
409 int gid;
410
411 wxChar *uname;
412 wxChar *gname;
413 };
414
415 wxTarUser::wxTarUser()
416 {
417 #ifdef __UNIX__
418 uid = getuid();
419 gid = getgid();
420 wxString usr = wxTarUserName(uid);
421 wxString grp = wxTarGroupName(gid);
422 #else
423 uid = 0;
424 gid = 0;
425 wxString usr = wxGetUserId();
426 wxString grp = _("unknown");
427 #endif
428
429 uname = new wxChar[usr.length() + 1];
430 wxStrcpy(uname, usr.c_str());
431
432 gname = new wxChar[grp.length() + 1];
433 wxStrcpy(gname, grp.c_str());
434 }
435
436 static const wxTarUser& wxGetTarUser()
437 {
438 #if wxUSE_THREADS
439 static wxCriticalSection cs;
440 wxCriticalSectionLocker lock(cs);
441 #endif
442 static wxTarUser tu;
443 return tu;
444 }
445
446 // ignore the size field for entry types 3, 4, 5 and 6
447 //
448 static inline wxFileOffset GetDataSize(const wxTarEntry& entry)
449 {
450 switch (entry.GetTypeFlag()) {
451 case wxTAR_CHRTYPE:
452 case wxTAR_BLKTYPE:
453 case wxTAR_DIRTYPE:
454 case wxTAR_FIFOTYPE:
455 return 0;
456 default:
457 return entry.GetSize();
458 }
459 }
460
461
462 /////////////////////////////////////////////////////////////////////////////
463 // Tar Entry
464 // Holds all the meta-data for a file in the tar
465
466 wxTarEntry::wxTarEntry(const wxString& name /*=wxEmptyString*/,
467 const wxDateTime& dt /*=wxDateTime::Now()*/,
468 wxFileOffset size /*=0*/)
469 : m_Mode(0644),
470 m_IsModeSet(false),
471 m_UserId(wxGetTarUser().uid),
472 m_GroupId(wxGetTarUser().gid),
473 m_Size(size),
474 m_Offset(wxInvalidOffset),
475 m_ModifyTime(dt),
476 m_TypeFlag(wxTAR_REGTYPE),
477 m_UserName(wxGetTarUser().uname),
478 m_GroupName(wxGetTarUser().gname),
479 m_DevMajor(~0),
480 m_DevMinor(~0)
481 {
482 if (!name.empty())
483 SetName(name);
484 }
485
486 wxTarEntry::~wxTarEntry()
487 {
488 }
489
490 wxTarEntry::wxTarEntry(const wxTarEntry& e)
491 : wxArchiveEntry(),
492 m_Name(e.m_Name),
493 m_Mode(e.m_Mode),
494 m_IsModeSet(e.m_IsModeSet),
495 m_UserId(e.m_UserId),
496 m_GroupId(e.m_GroupId),
497 m_Size(e.m_Size),
498 m_Offset(e.m_Offset),
499 m_ModifyTime(e.m_ModifyTime),
500 m_AccessTime(e.m_AccessTime),
501 m_CreateTime(e.m_CreateTime),
502 m_TypeFlag(e.m_TypeFlag),
503 m_LinkName(e.m_LinkName),
504 m_UserName(e.m_UserName),
505 m_GroupName(e.m_GroupName),
506 m_DevMajor(e.m_DevMajor),
507 m_DevMinor(e.m_DevMinor)
508 {
509 }
510
511 wxTarEntry& wxTarEntry::operator=(const wxTarEntry& e)
512 {
513 if (&e != this) {
514 m_Name = e.m_Name;
515 m_Mode = e.m_Mode;
516 m_IsModeSet = e.m_IsModeSet;
517 m_UserId = e.m_UserId;
518 m_GroupId = e.m_GroupId;
519 m_Size = e.m_Size;
520 m_Offset = e.m_Offset;
521 m_ModifyTime = e.m_ModifyTime;
522 m_AccessTime = e.m_AccessTime;
523 m_CreateTime = e.m_CreateTime;
524 m_TypeFlag = e.m_TypeFlag;
525 m_LinkName = e.m_LinkName;
526 m_UserName = e.m_UserName;
527 m_GroupName = e.m_GroupName;
528 m_DevMajor = e.m_DevMajor;
529 m_DevMinor = e.m_DevMinor;
530 }
531 return *this;
532 }
533
534 wxString wxTarEntry::GetName(wxPathFormat format /*=wxPATH_NATIVE*/) const
535 {
536 bool isDir = IsDir() && !m_Name.empty();
537
538 // optimisations for common (and easy) cases
539 switch (wxFileName::GetFormat(format)) {
540 case wxPATH_DOS:
541 {
542 wxString name(isDir ? m_Name + _T("\\") : m_Name);
543 for (size_t i = 0; i < name.length(); i++)
544 if (name[i] == _T('/'))
545 name[i] = _T('\\');
546 return name;
547 }
548
549 case wxPATH_UNIX:
550 return isDir ? m_Name + _T("/") : m_Name;
551
552 default:
553 ;
554 }
555
556 wxFileName fn;
557
558 if (isDir)
559 fn.AssignDir(m_Name, wxPATH_UNIX);
560 else
561 fn.Assign(m_Name, wxPATH_UNIX);
562
563 return fn.GetFullPath(format);
564 }
565
566 void wxTarEntry::SetName(const wxString& name, wxPathFormat format)
567 {
568 bool isDir;
569 m_Name = GetInternalName(name, format, &isDir);
570 SetIsDir(isDir);
571 }
572
573 // Static - Internally tars and zips use forward slashes for the path
574 // separator, absolute paths aren't allowed, and directory names have a
575 // trailing slash. This function converts a path into this internal format,
576 // but without a trailing slash for a directory.
577 //
578 wxString wxTarEntry::GetInternalName(const wxString& name,
579 wxPathFormat format /*=wxPATH_NATIVE*/,
580 bool *pIsDir /*=NULL*/)
581 {
582 wxString internal;
583
584 if (wxFileName::GetFormat(format) != wxPATH_UNIX)
585 internal = wxFileName(name, format).GetFullPath(wxPATH_UNIX);
586 else
587 internal = name;
588
589 bool isDir = !internal.empty() && internal.Last() == '/';
590 if (pIsDir)
591 *pIsDir = isDir;
592 if (isDir)
593 internal.erase(internal.length() - 1);
594
595 while (!internal.empty() && *internal.begin() == '/')
596 internal.erase(0, 1);
597 while (!internal.empty() && internal.compare(0, 2, _T("./")) == 0)
598 internal.erase(0, 2);
599 if (internal == _T(".") || internal == _T(".."))
600 internal = wxEmptyString;
601
602 return internal;
603 }
604
605 bool wxTarEntry::IsDir() const
606 {
607 return m_TypeFlag == wxTAR_DIRTYPE;
608 }
609
610 void wxTarEntry::SetIsDir(bool isDir)
611 {
612 if (isDir)
613 m_TypeFlag = wxTAR_DIRTYPE;
614 else if (m_TypeFlag == wxTAR_DIRTYPE)
615 m_TypeFlag = wxTAR_REGTYPE;
616 }
617
618 void wxTarEntry::SetIsReadOnly(bool isReadOnly)
619 {
620 if (isReadOnly)
621 m_Mode &= ~0222;
622 else
623 m_Mode |= 0200;
624 }
625
626 int wxTarEntry::GetMode() const
627 {
628 if (m_IsModeSet || !IsDir())
629 return m_Mode;
630 else
631 return m_Mode | 0111;
632
633 }
634
635 void wxTarEntry::SetMode(int mode)
636 {
637 m_Mode = mode & 07777;
638 m_IsModeSet = true;
639 }
640
641
642 /////////////////////////////////////////////////////////////////////////////
643 // Input stream
644
645 wxDECLARE_SCOPED_PTR(wxTarEntry, wxTarEntryPtr_)
646 wxDEFINE_SCOPED_PTR (wxTarEntry, wxTarEntryPtr_)
647
648 wxTarInputStream::wxTarInputStream(wxInputStream& stream,
649 wxMBConv& conv /*=wxConvLocal*/)
650 : wxArchiveInputStream(stream, conv)
651 {
652 Init();
653 }
654
655 wxTarInputStream::wxTarInputStream(wxInputStream *stream,
656 wxMBConv& conv /*=wxConvLocal*/)
657 : wxArchiveInputStream(stream, conv)
658 {
659 Init();
660 }
661
662 void wxTarInputStream::Init()
663 {
664 m_pos = wxInvalidOffset;
665 m_offset = 0;
666 m_size = wxInvalidOffset;
667 m_sumType = SUM_UNKNOWN;
668 m_tarType = TYPE_USTAR;
669 m_hdr = new wxTarHeaderBlock;
670 m_HeaderRecs = NULL;
671 m_GlobalHeaderRecs = NULL;
672 m_lasterror = m_parent_i_stream->GetLastError();
673 }
674
675 wxTarInputStream::~wxTarInputStream()
676 {
677 delete m_hdr;
678 delete m_HeaderRecs;
679 delete m_GlobalHeaderRecs;
680 }
681
682 wxTarEntry *wxTarInputStream::GetNextEntry()
683 {
684 m_lasterror = ReadHeaders();
685
686 if (!IsOk())
687 return NULL;
688
689 wxTarEntryPtr_ entry(new wxTarEntry);
690
691 entry->SetMode(GetHeaderNumber(TAR_MODE));
692 entry->SetUserId(GetHeaderNumber(TAR_UID));
693 entry->SetGroupId(GetHeaderNumber(TAR_UID));
694 entry->SetSize(GetHeaderNumber(TAR_SIZE));
695
696 entry->SetOffset(m_offset);
697
698 entry->SetDateTime(GetHeaderDate(_T("mtime")));
699 entry->SetAccessTime(GetHeaderDate(_T("atime")));
700 entry->SetCreateTime(GetHeaderDate(_T("ctime")));
701
702 entry->SetTypeFlag(*m_hdr->Get(TAR_TYPEFLAG));
703 bool isDir = entry->IsDir();
704
705 entry->SetLinkName(GetHeaderString(TAR_LINKNAME));
706
707 if (m_tarType != TYPE_OLDTAR) {
708 entry->SetUserName(GetHeaderString(TAR_UNAME));
709 entry->SetGroupName(GetHeaderString(TAR_GNAME));
710
711 entry->SetDevMajor(GetHeaderNumber(TAR_DEVMAJOR));
712 entry->SetDevMinor(GetHeaderNumber(TAR_DEVMINOR));
713 }
714
715 entry->SetName(GetHeaderPath(), wxPATH_UNIX);
716 if (isDir)
717 entry->SetIsDir();
718
719 if (m_HeaderRecs)
720 m_HeaderRecs->clear();
721
722 m_size = GetDataSize(*entry);
723 m_pos = 0;
724
725 return entry.release();
726 }
727
728 bool wxTarInputStream::OpenEntry(wxTarEntry& entry)
729 {
730 wxFileOffset offset = entry.GetOffset();
731
732 if (GetLastError() != wxSTREAM_READ_ERROR
733 && m_parent_i_stream->IsSeekable()
734 && m_parent_i_stream->SeekI(offset) == offset)
735 {
736 m_offset = offset;
737 m_size = GetDataSize(entry);
738 m_pos = 0;
739 m_lasterror = wxSTREAM_NO_ERROR;
740 return true;
741 } else {
742 m_lasterror = wxSTREAM_READ_ERROR;
743 return false;
744 }
745 }
746
747 bool wxTarInputStream::OpenEntry(wxArchiveEntry& entry)
748 {
749 wxTarEntry *tarEntry = wxStaticCast(&entry, wxTarEntry);
750 return tarEntry ? OpenEntry(*tarEntry) : false;
751 }
752
753 bool wxTarInputStream::CloseEntry()
754 {
755 if (m_lasterror == wxSTREAM_READ_ERROR)
756 return false;
757 if (!IsOpened())
758 return true;
759
760 wxFileOffset size = RoundUpSize(m_size);
761 wxFileOffset remainder = size - m_pos;
762
763 if (remainder && m_parent_i_stream->IsSeekable()) {
764 wxLogNull nolog;
765 if (m_parent_i_stream->SeekI(remainder, wxFromCurrent)
766 != wxInvalidOffset)
767 remainder = 0;
768 }
769
770 if (remainder) {
771 const int BUFSIZE = 8192;
772 wxCharBuffer buf(BUFSIZE);
773
774 while (remainder > 0 && m_parent_i_stream->IsOk())
775 remainder -= m_parent_i_stream->Read(
776 buf.data(), wxMin(BUFSIZE, remainder)).LastRead();
777 }
778
779 m_pos = wxInvalidOffset;
780 m_offset += size;
781 m_lasterror = m_parent_i_stream->GetLastError();
782
783 return IsOk();
784 }
785
786 wxStreamError wxTarInputStream::ReadHeaders()
787 {
788 if (!CloseEntry())
789 return wxSTREAM_READ_ERROR;
790
791 bool done = false;
792
793 while (!done) {
794 m_hdr->Read(*m_parent_i_stream);
795 if (m_parent_i_stream->Eof())
796 wxLogError(_("incomplete header block in tar"));
797 if (!*m_parent_i_stream)
798 return wxSTREAM_READ_ERROR;
799 m_offset += TAR_BLOCKSIZE;
800
801 // an all-zero header marks the end of the tar
802 if (m_hdr->IsAllZeros())
803 return wxSTREAM_EOF;
804
805 // the checksum is supposed to be the unsigned sum of the header bytes,
806 // but there have been versions of tar that used the signed sum, so
807 // accept that too, but only if used throughout.
808 wxUint32 chksum = m_hdr->GetOctal(TAR_CHKSUM);
809 bool ok = false;
810
811 if (m_sumType != SUM_SIGNED) {
812 ok = chksum == m_hdr->Sum();
813 if (m_sumType == SUM_UNKNOWN)
814 m_sumType = ok ? SUM_UNSIGNED : SUM_SIGNED;
815 }
816 if (m_sumType == SUM_SIGNED)
817 ok = chksum == m_hdr->Sum(true);
818 if (!ok) {
819 wxLogError(_("checksum failure reading tar header block"));
820 return wxSTREAM_READ_ERROR;
821 }
822
823 if (strcmp(m_hdr->Get(TAR_MAGIC), USTAR_MAGIC) == 0)
824 m_tarType = TYPE_USTAR;
825 else if (strcmp(m_hdr->Get(TAR_MAGIC), GNU_MAGIC) == 0 &&
826 strcmp(m_hdr->Get(TAR_VERSION), GNU_VERION) == 0)
827 m_tarType = TYPE_GNUTAR;
828 else
829 m_tarType = TYPE_OLDTAR;
830
831 if (m_tarType != TYPE_USTAR)
832 break;
833
834 switch (*m_hdr->Get(TAR_TYPEFLAG)) {
835 case 'g': ReadExtendedHeader(m_GlobalHeaderRecs); break;
836 case 'x': ReadExtendedHeader(m_HeaderRecs); break;
837 default: done = true;
838 }
839 }
840
841 return wxSTREAM_NO_ERROR;
842 }
843
844 wxString wxTarInputStream::GetExtendedHeader(const wxString& key) const
845 {
846 wxTarHeaderRecords::iterator it;
847
848 // look at normal extended header records first
849 if (m_HeaderRecs) {
850 it = m_HeaderRecs->find(key);
851 if (it != m_HeaderRecs->end())
852 return wxString(it->second.wc_str(wxConvUTF8), GetConv());
853 }
854
855 // if not found, look at the global header records
856 if (m_GlobalHeaderRecs) {
857 it = m_GlobalHeaderRecs->find(key);
858 if (it != m_GlobalHeaderRecs->end())
859 return wxString(it->second.wc_str(wxConvUTF8), GetConv());
860 }
861
862 return wxEmptyString;
863 }
864
865 wxString wxTarInputStream::GetHeaderPath() const
866 {
867 wxString path;
868
869 if ((path = GetExtendedHeader(_T("path"))) != wxEmptyString)
870 return path;
871
872 path = wxString(m_hdr->Get(TAR_NAME), GetConv());
873 if (m_tarType != TYPE_USTAR)
874 return path;
875
876 const char *prefix = m_hdr->Get(TAR_PREFIX);
877 return *prefix ? wxString(prefix, GetConv()) + _T("/") + path : path;
878 }
879
880 wxDateTime wxTarInputStream::GetHeaderDate(const wxString& key) const
881 {
882 wxString value;
883
884 // try extended header, stored as decimal seconds since the epoch
885 if ((value = GetExtendedHeader(key)) != wxEmptyString) {
886 wxLongLong ll;
887 ll.Assign(wxAtof(value) * 1000.0);
888 return ll;
889 }
890
891 if (key == _T("mtime"))
892 return wxLongLong(m_hdr->GetOctal(TAR_MTIME)) * 1000L;
893
894 return wxDateTime();
895 }
896
897 wxTarNumber wxTarInputStream::GetHeaderNumber(int id) const
898 {
899 wxString value;
900
901 if ((value = GetExtendedHeader(m_hdr->Name(id))) != wxEmptyString) {
902 wxTarNumber n = 0;
903 wxString::const_iterator p = value.begin();
904 while (*p == ' ' && p != value.end())
905 p++;
906 while (isdigit(*p))
907 n = n * 10 + (*p++ - '0');
908 return n;
909 } else {
910 return m_hdr->GetOctal(id);
911 }
912 }
913
914 wxString wxTarInputStream::GetHeaderString(int id) const
915 {
916 wxString value;
917
918 if ((value = GetExtendedHeader(m_hdr->Name(id))) != wxEmptyString)
919 return value;
920
921 return wxString(m_hdr->Get(id), GetConv());
922 }
923
924 // An extended header consists of one or more records, each constructed:
925 // "%d %s=%s\n", <length>, <keyword>, <value>
926 // <length> is the byte length, <keyword> and <value> are UTF-8
927
928 bool wxTarInputStream::ReadExtendedHeader(wxTarHeaderRecords*& recs)
929 {
930 if (!recs)
931 recs = new wxTarHeaderRecords;
932
933 // round length up to a whole number of blocks
934 size_t len = m_hdr->GetOctal(TAR_SIZE);
935 size_t size = RoundUpSize(len);
936
937 // read in the whole header since it should be small
938 wxCharBuffer buf(size);
939 size_t lastread = m_parent_i_stream->Read(buf.data(), size).LastRead();
940 if (lastread < len)
941 len = lastread;
942 buf.data()[len] = 0;
943 m_offset += lastread;
944
945 size_t recPos, recSize;
946 bool ok = true;
947
948 for (recPos = 0; recPos < len && ok; recPos += recSize) {
949 char *pRec = buf.data() + recPos;
950 char *p = pRec;
951
952 // read the record size (byte count in ascii decimal)
953 recSize = 0;
954 while (isdigit((unsigned char) *p))
955 recSize = recSize * 10 + *p++ - '0';
956
957 // validity checks
958 if (recPos + recSize > len)
959 break;
960 if (recSize < p - pRec + (size_t)3 || *p != ' '
961 || pRec[recSize - 1] != '\012') {
962 ok = false;
963 continue;
964 }
965
966 // replace the final '\n' with a nul, to terminate value
967 pRec[recSize - 1] = 0;
968 // the key is here, following the space
969 char *pKey = ++p;
970
971 // look forward for the '=', the value follows
972 while (*p && *p != '=')
973 p++;
974 if (!*p) {
975 ok = false;
976 continue;
977 }
978 // replace the '=' with a nul, to terminate the key
979 *p++ = 0;
980
981 wxString key(wxConvUTF8.cMB2WC(pKey), GetConv());
982 wxString value(wxConvUTF8.cMB2WC(p), GetConv());
983
984 // an empty value unsets a previously given value
985 if (value.empty())
986 recs->erase(key);
987 else
988 (*recs)[key] = value;
989 }
990
991 if (!ok || recPos < len || size != lastread) {
992 wxLogWarning(_("invalid data in extended tar header"));
993 return false;
994 }
995
996 return true;
997 }
998
999 wxFileOffset wxTarInputStream::OnSysSeek(wxFileOffset pos, wxSeekMode mode)
1000 {
1001 if (!IsOpened()) {
1002 wxLogError(_("tar entry not open"));
1003 m_lasterror = wxSTREAM_READ_ERROR;
1004 }
1005 if (!IsOk())
1006 return wxInvalidOffset;
1007
1008 switch (mode) {
1009 case wxFromStart: break;
1010 case wxFromCurrent: pos += m_pos; break;
1011 case wxFromEnd: pos += m_size; break;
1012 }
1013
1014 if (pos < 0 || m_parent_i_stream->SeekI(m_offset + pos) == wxInvalidOffset)
1015 return wxInvalidOffset;
1016
1017 m_pos = pos;
1018 return m_pos;
1019 }
1020
1021 size_t wxTarInputStream::OnSysRead(void *buffer, size_t size)
1022 {
1023 if (!IsOpened()) {
1024 wxLogError(_("tar entry not open"));
1025 m_lasterror = wxSTREAM_READ_ERROR;
1026 }
1027 if (!IsOk() || !size)
1028 return 0;
1029
1030 if (m_pos >= m_size)
1031 size = 0;
1032 else if (m_pos + size > m_size + (size_t)0)
1033 size = m_size - m_pos;
1034
1035 size_t lastread = m_parent_i_stream->Read(buffer, size).LastRead();
1036 m_pos += lastread;
1037
1038 if (m_pos >= m_size) {
1039 m_lasterror = wxSTREAM_EOF;
1040 } else if (!m_parent_i_stream->IsOk()) {
1041 // any other error will have been reported by the underlying stream
1042 if (m_parent_i_stream->Eof())
1043 wxLogError(_("unexpected end of file"));
1044 m_lasterror = wxSTREAM_READ_ERROR;
1045 }
1046
1047 return lastread;
1048 }
1049
1050
1051 /////////////////////////////////////////////////////////////////////////////
1052 // Output stream
1053
1054 wxTarOutputStream::wxTarOutputStream(wxOutputStream& stream,
1055 wxTarFormat format /*=wxTAR_PAX*/,
1056 wxMBConv& conv /*=wxConvLocal*/)
1057 : wxArchiveOutputStream(stream, conv)
1058 {
1059 Init(format);
1060 }
1061
1062 wxTarOutputStream::wxTarOutputStream(wxOutputStream *stream,
1063 wxTarFormat format /*=wxTAR_PAX*/,
1064 wxMBConv& conv /*=wxConvLocal*/)
1065 : wxArchiveOutputStream(stream, conv)
1066 {
1067 Init(format);
1068 }
1069
1070 void wxTarOutputStream::Init(wxTarFormat format)
1071 {
1072 m_pos = wxInvalidOffset;
1073 m_maxpos = wxInvalidOffset;
1074 m_size = wxInvalidOffset;
1075 m_headpos = wxInvalidOffset;
1076 m_datapos = wxInvalidOffset;
1077 m_tarstart = wxInvalidOffset;
1078 m_tarsize = 0;
1079 m_pax = format == wxTAR_PAX;
1080 m_BlockingFactor = m_pax ? 10 : 20;
1081 m_chksum = 0;
1082 m_large = false;
1083 m_hdr = new wxTarHeaderBlock;
1084 m_hdr2 = NULL;
1085 m_extendedHdr = NULL;
1086 m_extendedSize = 0;
1087 m_lasterror = m_parent_o_stream->GetLastError();
1088 m_endrecWritten = false;
1089 }
1090
1091 wxTarOutputStream::~wxTarOutputStream()
1092 {
1093 Close();
1094 delete m_hdr;
1095 delete m_hdr2;
1096 delete [] m_extendedHdr;
1097 }
1098
1099 bool wxTarOutputStream::PutNextEntry(wxTarEntry *entry)
1100 {
1101 wxTarEntryPtr_ e(entry);
1102
1103 if (!CloseEntry())
1104 return false;
1105
1106 if (!m_tarsize) {
1107 wxLogNull nolog;
1108 m_tarstart = m_parent_o_stream->TellO();
1109 }
1110
1111 if (m_tarstart != wxInvalidOffset)
1112 m_headpos = m_tarstart + m_tarsize;
1113
1114 if (WriteHeaders(*e)) {
1115 m_pos = 0;
1116 m_maxpos = 0;
1117 m_size = GetDataSize(*e);
1118 if (m_tarstart != wxInvalidOffset)
1119 m_datapos = m_tarstart + m_tarsize;
1120
1121 // types that are not allowd any data
1122 const char nodata[] = {
1123 wxTAR_LNKTYPE, wxTAR_SYMTYPE, wxTAR_CHRTYPE, wxTAR_BLKTYPE,
1124 wxTAR_DIRTYPE, wxTAR_FIFOTYPE, 0
1125 };
1126 int typeflag = e->GetTypeFlag();
1127
1128 // pax does now allow data for wxTAR_LNKTYPE
1129 if (!m_pax || typeflag != wxTAR_LNKTYPE)
1130 if (strchr(nodata, typeflag) != NULL)
1131 CloseEntry();
1132 }
1133
1134 return IsOk();
1135 }
1136
1137 bool wxTarOutputStream::PutNextEntry(const wxString& name,
1138 const wxDateTime& dt,
1139 wxFileOffset size)
1140 {
1141 return PutNextEntry(new wxTarEntry(name, dt, size));
1142 }
1143
1144 bool wxTarOutputStream::PutNextDirEntry(const wxString& name,
1145 const wxDateTime& dt)
1146 {
1147 wxTarEntry *entry = new wxTarEntry(name, dt);
1148 entry->SetIsDir();
1149 return PutNextEntry(entry);
1150 }
1151
1152 bool wxTarOutputStream::PutNextEntry(wxArchiveEntry *entry)
1153 {
1154 wxTarEntry *tarEntry = wxStaticCast(entry, wxTarEntry);
1155 if (!tarEntry)
1156 delete entry;
1157 return PutNextEntry(tarEntry);
1158 }
1159
1160 bool wxTarOutputStream::CopyEntry(wxTarEntry *entry,
1161 wxTarInputStream& inputStream)
1162 {
1163 if (PutNextEntry(entry))
1164 Write(inputStream);
1165 return IsOk() && inputStream.Eof();
1166 }
1167
1168 bool wxTarOutputStream::CopyEntry(wxArchiveEntry *entry,
1169 wxArchiveInputStream& inputStream)
1170 {
1171 if (PutNextEntry(entry))
1172 Write(inputStream);
1173 return IsOk() && inputStream.Eof();
1174 }
1175
1176 bool wxTarOutputStream::CloseEntry()
1177 {
1178 if (!IsOpened())
1179 return true;
1180
1181 if (m_pos < m_maxpos) {
1182 wxASSERT(m_parent_o_stream->IsSeekable());
1183 m_parent_o_stream->SeekO(m_datapos + m_maxpos);
1184 m_lasterror = m_parent_o_stream->GetLastError();
1185 m_pos = m_maxpos;
1186 }
1187
1188 if (IsOk()) {
1189 wxFileOffset size = RoundUpSize(m_pos);
1190 if (size > m_pos) {
1191 memset(m_hdr, 0, size - m_pos);
1192 m_parent_o_stream->Write(m_hdr, size - m_pos);
1193 m_lasterror = m_parent_o_stream->GetLastError();
1194 }
1195 m_tarsize += size;
1196 }
1197
1198 if (IsOk() && m_pos != m_size)
1199 ModifyHeader();
1200
1201 m_pos = wxInvalidOffset;
1202 m_maxpos = wxInvalidOffset;
1203 m_size = wxInvalidOffset;
1204 m_headpos = wxInvalidOffset;
1205 m_datapos = wxInvalidOffset;
1206
1207 return IsOk();
1208 }
1209
1210 bool wxTarOutputStream::Close()
1211 {
1212 if (!CloseEntry() || (m_tarsize == 0 && m_endrecWritten))
1213 return false;
1214
1215 memset(m_hdr, 0, sizeof(*m_hdr));
1216 int count = (RoundUpSize(m_tarsize + 2 * TAR_BLOCKSIZE, m_BlockingFactor)
1217 - m_tarsize) / TAR_BLOCKSIZE;
1218 while (count--)
1219 m_parent_o_stream->Write(m_hdr, TAR_BLOCKSIZE);
1220
1221 m_tarsize = 0;
1222 m_tarstart = wxInvalidOffset;
1223 m_lasterror = m_parent_o_stream->GetLastError();
1224 m_endrecWritten = true;
1225 return IsOk();
1226 }
1227
1228 bool wxTarOutputStream::WriteHeaders(wxTarEntry& entry)
1229 {
1230 memset(m_hdr, 0, sizeof(*m_hdr));
1231
1232 SetHeaderPath(entry.GetName(wxPATH_UNIX));
1233
1234 SetHeaderNumber(TAR_MODE, entry.GetMode());
1235 SetHeaderNumber(TAR_UID, entry.GetUserId());
1236 SetHeaderNumber(TAR_GID, entry.GetGroupId());
1237
1238 if (entry.GetSize() == wxInvalidOffset)
1239 entry.SetSize(0);
1240 m_large = !SetHeaderNumber(TAR_SIZE, entry.GetSize());
1241
1242 SetHeaderDate(_T("mtime"), entry.GetDateTime());
1243 if (entry.GetAccessTime().IsValid())
1244 SetHeaderDate(_T("atime"), entry.GetAccessTime());
1245 if (entry.GetCreateTime().IsValid())
1246 SetHeaderDate(_T("ctime"), entry.GetCreateTime());
1247
1248 *m_hdr->Get(TAR_TYPEFLAG) = char(entry.GetTypeFlag());
1249
1250 strcpy(m_hdr->Get(TAR_MAGIC), USTAR_MAGIC);
1251 strcpy(m_hdr->Get(TAR_VERSION), USTAR_VERSION);
1252
1253 SetHeaderString(TAR_LINKNAME, entry.GetLinkName());
1254 SetHeaderString(TAR_UNAME, entry.GetUserName());
1255 SetHeaderString(TAR_GNAME, entry.GetGroupName());
1256
1257 if (~entry.GetDevMajor())
1258 SetHeaderNumber(TAR_DEVMAJOR, entry.GetDevMajor());
1259 if (~entry.GetDevMinor())
1260 SetHeaderNumber(TAR_DEVMINOR, entry.GetDevMinor());
1261
1262 m_chksum = m_hdr->Sum();
1263 m_hdr->SetOctal(TAR_CHKSUM, m_chksum);
1264 if (!m_large)
1265 m_chksum -= m_hdr->SumField(TAR_SIZE);
1266
1267 // The main header is now fully prepared so we know what extended headers
1268 // (if any) will be needed. Output any extended headers before writing
1269 // the main header.
1270 if (m_extendedHdr && *m_extendedHdr) {
1271 wxASSERT(m_pax);
1272 // the extended headers are written to the tar as a file entry,
1273 // so prepare a regular header block for the pseudo-file.
1274 if (!m_hdr2)
1275 m_hdr2 = new wxTarHeaderBlock;
1276 memset(m_hdr2, 0, sizeof(*m_hdr2));
1277
1278 // an old tar that doesn't understand extended headers will
1279 // extract it as a file, so give these fields reasonable values
1280 // so that the user will have access to read and remove it.
1281 m_hdr2->SetPath(PaxHeaderPath(_T("%d/PaxHeaders.%p/%f"),
1282 entry.GetName(wxPATH_UNIX)), GetConv());
1283 m_hdr2->SetOctal(TAR_MODE, 0600);
1284 strcpy(m_hdr2->Get(TAR_UID), m_hdr->Get(TAR_UID));
1285 strcpy(m_hdr2->Get(TAR_GID), m_hdr->Get(TAR_GID));
1286 size_t length = strlen(m_extendedHdr);
1287 m_hdr2->SetOctal(TAR_SIZE, length);
1288 strcpy(m_hdr2->Get(TAR_MTIME), m_hdr->Get(TAR_MTIME));
1289 *m_hdr2->Get(TAR_TYPEFLAG) = 'x';
1290 strcpy(m_hdr2->Get(TAR_MAGIC), USTAR_MAGIC);
1291 strcpy(m_hdr2->Get(TAR_VERSION), USTAR_VERSION);
1292 strcpy(m_hdr2->Get(TAR_UNAME), m_hdr->Get(TAR_UNAME));
1293 strcpy(m_hdr2->Get(TAR_GNAME), m_hdr->Get(TAR_GNAME));
1294
1295 m_hdr2->SetOctal(TAR_CHKSUM, m_hdr2->Sum());
1296
1297 m_hdr2->Write(*m_parent_o_stream);
1298 m_tarsize += TAR_BLOCKSIZE;
1299
1300 size_t rounded = RoundUpSize(length);
1301 memset(m_extendedHdr + length, 0, rounded - length);
1302 m_parent_o_stream->Write(m_extendedHdr, rounded);
1303 m_tarsize += rounded;
1304
1305 *m_extendedHdr = 0;
1306 }
1307
1308 // if don't have extended headers just report error
1309 if (!m_badfit.empty()) {
1310 wxASSERT(!m_pax);
1311 wxLogWarning(_("%s did not fit the tar header for entry '%s'"),
1312 m_badfit.c_str(), entry.GetName().c_str());
1313 m_badfit.clear();
1314 }
1315
1316 m_hdr->Write(*m_parent_o_stream);
1317 m_tarsize += TAR_BLOCKSIZE;
1318 m_lasterror = m_parent_o_stream->GetLastError();
1319
1320 return IsOk();
1321 }
1322
1323 wxString wxTarOutputStream::PaxHeaderPath(const wxString& format,
1324 const wxString& path)
1325 {
1326 wxString d = path.BeforeLast(_T('/'));
1327 wxString f = path.AfterLast(_T('/'));
1328 wxString ret;
1329
1330 if (d.empty())
1331 d = _T(".");
1332
1333 ret.reserve(format.length() + path.length() + 16);
1334
1335 size_t begin = 0;
1336 size_t end;
1337
1338 for (;;) {
1339 end = format.find('%', begin);
1340 if (end == wxString::npos || end + 1 >= format.length())
1341 break;
1342 ret << format.substr(begin, end - begin);
1343 switch ( format[end + 1].GetValue() ) {
1344 case 'd': ret << d; break;
1345 case 'f': ret << f; break;
1346 case 'p': ret << wxGetProcessId(); break;
1347 case '%': ret << _T("%"); break;
1348 }
1349 begin = end + 2;
1350 }
1351
1352 ret << format.substr(begin);
1353
1354 return ret;
1355 }
1356
1357 bool wxTarOutputStream::ModifyHeader()
1358 {
1359 wxFileOffset originalPos = wxInvalidOffset;
1360 wxFileOffset sizePos = wxInvalidOffset;
1361
1362 if (!m_large && m_headpos != wxInvalidOffset
1363 && m_parent_o_stream->IsSeekable())
1364 {
1365 wxLogNull nolog;
1366 originalPos = m_parent_o_stream->TellO();
1367 if (originalPos != wxInvalidOffset)
1368 sizePos =
1369 m_parent_o_stream->SeekO(m_headpos + m_hdr->Offset(TAR_SIZE));
1370 }
1371
1372 if (sizePos == wxInvalidOffset || !m_hdr->SetOctal(TAR_SIZE, m_pos)) {
1373 wxLogError(_("incorrect size given for tar entry"));
1374 m_lasterror = wxSTREAM_WRITE_ERROR;
1375 return false;
1376 }
1377
1378 m_chksum += m_hdr->SumField(TAR_SIZE);
1379 m_hdr->SetOctal(TAR_CHKSUM, m_chksum);
1380 wxFileOffset sumPos = m_headpos + m_hdr->Offset(TAR_CHKSUM);
1381
1382 return
1383 m_hdr->WriteField(*m_parent_o_stream, TAR_SIZE) &&
1384 m_parent_o_stream->SeekO(sumPos) == sumPos &&
1385 m_hdr->WriteField(*m_parent_o_stream, TAR_CHKSUM) &&
1386 m_parent_o_stream->SeekO(originalPos) == originalPos;
1387 }
1388
1389 void wxTarOutputStream::SetHeaderPath(const wxString& name)
1390 {
1391 if (!m_hdr->SetPath(name, GetConv()) || (m_pax && !name.IsAscii()))
1392 SetExtendedHeader(_T("path"), name);
1393 }
1394
1395 bool wxTarOutputStream::SetHeaderNumber(int id, wxTarNumber n)
1396 {
1397 if (m_hdr->SetOctal(id, n)) {
1398 return true;
1399 } else {
1400 SetExtendedHeader(m_hdr->Name(id), wxLongLong(n).ToString());
1401 return false;
1402 }
1403 }
1404
1405 void wxTarOutputStream::SetHeaderString(int id, const wxString& str)
1406 {
1407 strncpy(m_hdr->Get(id), str.mb_str(GetConv()), m_hdr->Len(id));
1408 if (str.length() > m_hdr->Len(id))
1409 SetExtendedHeader(m_hdr->Name(id), str);
1410 }
1411
1412 void wxTarOutputStream::SetHeaderDate(const wxString& key,
1413 const wxDateTime& datetime)
1414 {
1415 wxLongLong ll = datetime.IsValid() ? datetime.GetValue() : wxLongLong(0);
1416 wxLongLong secs = ll / 1000L;
1417
1418 if (key != _T("mtime")
1419 || !m_hdr->SetOctal(TAR_MTIME, wxTarNumber(secs.GetValue()))
1420 || secs <= 0 || secs >= 0x7fffffff)
1421 {
1422 wxString str;
1423 if (ll >= LONG_MIN && ll <= LONG_MAX) {
1424 str.Printf(_T("%g"), ll.ToLong() / 1000.0);
1425 } else {
1426 str = ll.ToString();
1427 str.insert(str.end() - 3, '.');
1428 }
1429 SetExtendedHeader(key, str);
1430 }
1431 }
1432
1433 void wxTarOutputStream::SetExtendedHeader(const wxString& key,
1434 const wxString& value)
1435 {
1436 if (m_pax) {
1437 #if wxUSE_UNICODE
1438 const wxCharBuffer utf_key = key.utf8_str();
1439 const wxCharBuffer utf_value = value.utf8_str();
1440 #else
1441 const wxWX2WCbuf wide_key = key.wc_str(GetConv());
1442 const wxCharBuffer utf_key = wxConvUTF8.cWC2MB(wide_key);
1443
1444 const wxWX2WCbuf wide_value = value.wc_str(GetConv());
1445 const wxCharBuffer utf_value = wxConvUTF8.cWC2MB(wide_value);
1446 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
1447
1448 // a small buffer to format the length field in
1449 char buf[32];
1450 // length of "99<space><key>=<value>\n"
1451 unsigned long length = strlen(utf_value) + strlen(utf_key) + 5;
1452 sprintf(buf, "%lu", length);
1453 // the length includes itself
1454 size_t lenlen = strlen(buf);
1455 if (lenlen != 2) {
1456 length += lenlen - 2;
1457 sprintf(buf, "%lu", length);
1458 if (strlen(buf) > lenlen)
1459 sprintf(buf, "%lu", ++length);
1460 }
1461
1462 // reallocate m_extendedHdr if it's not big enough
1463 if (m_extendedSize < length) {
1464 size_t rounded = RoundUpSize(length);
1465 m_extendedSize <<= 1;
1466 if (rounded > m_extendedSize)
1467 m_extendedSize = rounded;
1468 char *oldHdr = m_extendedHdr;
1469 m_extendedHdr = new char[m_extendedSize];
1470 if (oldHdr) {
1471 strcpy(m_extendedHdr, oldHdr);
1472 delete oldHdr;
1473 } else {
1474 *m_extendedHdr = 0;
1475 }
1476 }
1477
1478 // append the new record
1479 char *append = strchr(m_extendedHdr, 0);
1480 sprintf(append, "%s %s=%s\012", buf,
1481 (const char*)utf_key, (const char*)utf_value);
1482 }
1483 else {
1484 // if not pax then make a list of fields to report as errors
1485 if (!m_badfit.empty())
1486 m_badfit += _T(", ");
1487 m_badfit += key;
1488 }
1489 }
1490
1491 void wxTarOutputStream::Sync()
1492 {
1493 m_parent_o_stream->Sync();
1494 }
1495
1496 wxFileOffset wxTarOutputStream::OnSysSeek(wxFileOffset pos, wxSeekMode mode)
1497 {
1498 if (!IsOpened()) {
1499 wxLogError(_("tar entry not open"));
1500 m_lasterror = wxSTREAM_WRITE_ERROR;
1501 }
1502 if (!IsOk() || m_datapos == wxInvalidOffset)
1503 return wxInvalidOffset;
1504
1505 switch (mode) {
1506 case wxFromStart: break;
1507 case wxFromCurrent: pos += m_pos; break;
1508 case wxFromEnd: pos += m_maxpos; break;
1509 }
1510
1511 if (pos < 0 || m_parent_o_stream->SeekO(m_datapos + pos) == wxInvalidOffset)
1512 return wxInvalidOffset;
1513
1514 m_pos = pos;
1515 return m_pos;
1516 }
1517
1518 size_t wxTarOutputStream::OnSysWrite(const void *buffer, size_t size)
1519 {
1520 if (!IsOpened()) {
1521 wxLogError(_("tar entry not open"));
1522 m_lasterror = wxSTREAM_WRITE_ERROR;
1523 }
1524 if (!IsOk() || !size)
1525 return 0;
1526
1527 size_t lastwrite = m_parent_o_stream->Write(buffer, size).LastWrite();
1528 m_pos += lastwrite;
1529 if (m_pos > m_maxpos)
1530 m_maxpos = m_pos;
1531
1532 if (lastwrite != size)
1533 m_lasterror = wxSTREAM_WRITE_ERROR;
1534
1535 return lastwrite;
1536 }
1537
1538 #endif // wxUSE_TARSTREAM