1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Streams for Tar files
4 // Author: Mike Wetherell
6 // Copyright: (c) 2004 Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
19 #include "wx/tarstrm.h"
27 #include "wx/buffer.h"
28 #include "wx/datetime.h"
29 #include "wx/scopedptr.h"
30 #include "wx/filename.h"
31 #include "wx/thread.h"
41 /////////////////////////////////////////////////////////////////////////////
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
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
= " ";
89 IMPLEMENT_DYNAMIC_CLASS(wxTarEntry
, wxArchiveEntry
)
90 IMPLEMENT_DYNAMIC_CLASS(wxTarClassFactory
, wxArchiveClassFactory
)
93 /////////////////////////////////////////////////////////////////////////////
96 static wxTarClassFactory g_wxTarClassFactory
;
98 wxTarClassFactory::wxTarClassFactory()
100 if (this == &g_wxTarClassFactory
)
104 const wxChar
* const *
105 wxTarClassFactory::GetProtocols(wxStreamProtocolType type
) const
107 static const wxChar
*protocols
[] = { wxT("tar"), NULL
};
108 static const wxChar
*mimetypes
[] = { wxT("application/x-tar"), NULL
};
109 static const wxChar
*fileexts
[] = { wxT(".tar"), NULL
};
110 static const wxChar
*empty
[] = { NULL
};
113 case wxSTREAM_PROTOCOL
: return protocols
;
114 case wxSTREAM_MIMETYPE
: return mimetypes
;
115 case wxSTREAM_FILEEXT
: return fileexts
;
116 default: return empty
;
121 /////////////////////////////////////////////////////////////////////////////
124 typedef wxFileOffset wxTarNumber
;
126 struct wxTarField
{ const wxChar
*name
; int pos
; };
128 class wxTarHeaderBlock
132 { memset(data
, 0, sizeof(data
)); }
133 wxTarHeaderBlock(const wxTarHeaderBlock
& hb
)
134 { memcpy(data
, hb
.data
, sizeof(data
)); }
136 bool Read(wxInputStream
& in
);
137 bool Write(wxOutputStream
& out
);
138 inline bool WriteField(wxOutputStream
& out
, int id
);
140 bool IsAllZeros() const;
141 wxUint32
Sum(bool SignedSum
= false);
142 wxUint32
SumField(int id
);
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
; }
149 bool SetOctal(int id
, wxTarNumber n
);
150 wxTarNumber
GetOctal(int id
);
151 bool SetPath(const wxString
& name
, wxMBConv
& conv
);
154 char data
[TAR_BLOCKSIZE
+ TAR_NUMFIELDS
];
155 static const wxTarField fields
[];
159 wxDEFINE_SCOPED_PTR_TYPE(wxTarHeaderBlock
)
161 // A table giving the field names and offsets in a tar header block
162 const wxTarField
wxTarHeaderBlock::fields
[] =
164 { wxT("name"), 0 }, // 100
165 { wxT("mode"), 100 }, // 8
166 { wxT("uid"), 108 }, // 8
167 { wxT("gid"), 116 }, // 8
168 { wxT("size"), 124 }, // 12
169 { wxT("mtime"), 136 }, // 12
170 { wxT("chksum"), 148 }, // 8
171 { wxT("typeflag"), 156 }, // 1
172 { wxT("linkname"), 157 }, // 100
173 { wxT("magic"), 257 }, // 6
174 { wxT("version"), 263 }, // 2
175 { wxT("uname"), 265 }, // 32
176 { wxT("gname"), 297 }, // 32
177 { wxT("devmajor"), 329 }, // 8
178 { wxT("devminor"), 337 }, // 8
179 { wxT("prefix"), 345 }, // 155
180 { wxT("unused"), 500 }, // 12
181 { NULL
, TAR_BLOCKSIZE
}
184 void wxTarHeaderBlock::check()
187 wxCOMPILE_TIME_ASSERT(
188 WXSIZEOF(fields
) == TAR_NUMFIELDS
+ 1,
189 Wrong_number_of_elements_in_fields_table
194 bool wxTarHeaderBlock::IsAllZeros() const
196 const char *p
= data
;
197 for (size_t i
= 0; i
< sizeof(data
); i
++)
203 wxUint32
wxTarHeaderBlock::Sum(bool SignedSum
/*=false*/)
205 // the chksum field itself should be blanks during the calculation
206 memset(Get(TAR_CHKSUM
), ' ', Len(TAR_CHKSUM
));
207 const char *p
= data
;
211 for (size_t i
= 0; i
< sizeof(data
); i
++)
212 n
+= (signed char)p
[i
];
214 for (size_t i
= 0; i
< sizeof(data
); i
++)
215 n
+= (unsigned char)p
[i
];
220 wxUint32
wxTarHeaderBlock::SumField(int id
)
222 unsigned char *p
= (unsigned char*)Get(id
);
223 unsigned char *q
= p
+ Len(id
);
232 bool wxTarHeaderBlock::Read(wxInputStream
& in
)
236 for (int id
= 0; id
< TAR_NUMFIELDS
&& ok
; id
++)
237 ok
= in
.Read(Get(id
), Len(id
)).LastRead() == Len(id
);
242 bool wxTarHeaderBlock::Write(wxOutputStream
& out
)
246 for (int id
= 0; id
< TAR_NUMFIELDS
&& ok
; id
++)
247 ok
= WriteField(out
, id
);
252 inline bool wxTarHeaderBlock::WriteField(wxOutputStream
& out
, int id
)
254 return out
.Write(Get(id
), Len(id
)).LastWrite() == Len(id
);
257 wxTarNumber
wxTarHeaderBlock::GetOctal(int id
)
260 const char *p
= Get(id
);
263 while (*p
>= '0' && *p
< '8')
264 n
= (n
<< 3) | (*p
++ - '0');
268 bool wxTarHeaderBlock::SetOctal(int id
, wxTarNumber n
)
270 // set an octal field, return true if the number fits
271 char *field
= Get(id
);
272 char *p
= field
+ Len(id
);
275 *--p
= char('0' + (n
& 7));
281 bool wxTarHeaderBlock::SetPath(const wxString
& name
, wxMBConv
& conv
)
283 bool badconv
= false;
286 wxCharBuffer nameBuf
= name
.mb_str(conv
);
288 // if the conversion fails make an approximation
291 size_t len
= name
.length();
292 wxCharBuffer
approx(len
);
293 for (size_t i
= 0; i
< len
; i
++)
296 approx
.data()[i
] = c
& ~0x7F ? '_' : c
;
301 const char *mbName
= nameBuf
;
303 const char *mbName
= name
.c_str();
308 bool notGoingToFit
= false;
309 size_t len
= strlen(mbName
);
310 size_t maxname
= Len(TAR_NAME
);
311 size_t maxprefix
= Len(TAR_PREFIX
);
316 fits
= i
< maxprefix
&& len
- i
<= maxname
;
319 const char *p
= strchr(mbName
+ i
, '/');
321 nexti
= p
- mbName
+ 1;
322 if (!p
|| nexti
- 1 > maxprefix
)
323 notGoingToFit
= true;
326 if (fits
|| notGoingToFit
) {
327 strncpy(Get(TAR_NAME
), mbName
+ i
, maxname
);
329 strncpy(Get(TAR_PREFIX
), mbName
, i
- 1);
336 return fits
&& !badconv
;
340 /////////////////////////////////////////////////////////////////////////////
343 static wxFileOffset
RoundUpSize(wxFileOffset size
, int factor
= 1)
345 wxFileOffset chunk
= TAR_BLOCKSIZE
* factor
;
346 return ((size
+ chunk
- 1) / chunk
) * chunk
;
351 static wxString
wxTarUserName(int uid
)
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));
360 size_t bufsize
= 1024;
362 wxCharBuffer
buf(bufsize
);
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
);
369 if ((ppw
= getpwuid(uid
)) != NULL
)
370 return wxString(ppw
->pw_name
, wxConvLibc
);
375 static wxString
wxTarGroupName(int gid
)
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));
383 size_t bufsize
= 1024;
385 wxCharBuffer
buf(bufsize
);
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
);
392 if ((pgr
= getgrgid(gid
)) != NULL
)
393 return wxString(pgr
->gr_name
, wxConvLibc
);
400 // Cache the user and group names since getting them can be expensive,
401 // get both names and ids at the same time.
406 ~wxTarUser() { delete [] uname
; delete [] gname
; }
415 wxTarUser::wxTarUser()
420 wxString usr
= wxTarUserName(uid
);
421 wxString grp
= wxTarGroupName(gid
);
425 wxString usr
= wxGetUserId();
426 wxString grp
= _("unknown");
429 uname
= new wxChar
[usr
.length() + 1];
430 wxStrcpy(uname
, usr
.c_str());
432 gname
= new wxChar
[grp
.length() + 1];
433 wxStrcpy(gname
, grp
.c_str());
436 static const wxTarUser
& wxGetTarUser()
439 static wxCriticalSection cs
;
440 wxCriticalSectionLocker
lock(cs
);
446 // ignore the size field for entry types 3, 4, 5 and 6
448 static inline wxFileOffset
GetDataSize(const wxTarEntry
& entry
)
450 switch (entry
.GetTypeFlag()) {
457 return entry
.GetSize();
462 /////////////////////////////////////////////////////////////////////////////
464 // Holds all the meta-data for a file in the tar
466 wxTarEntry::wxTarEntry(const wxString
& name
/*=wxEmptyString*/,
467 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
468 wxFileOffset size
/*=0*/)
471 m_UserId(wxGetTarUser().uid
),
472 m_GroupId(wxGetTarUser().gid
),
474 m_Offset(wxInvalidOffset
),
476 m_TypeFlag(wxTAR_REGTYPE
),
477 m_UserName(wxGetTarUser().uname
),
478 m_GroupName(wxGetTarUser().gname
),
486 wxTarEntry::~wxTarEntry()
490 wxTarEntry::wxTarEntry(const wxTarEntry
& e
)
494 m_IsModeSet(e
.m_IsModeSet
),
495 m_UserId(e
.m_UserId
),
496 m_GroupId(e
.m_GroupId
),
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
)
511 wxTarEntry
& wxTarEntry::operator=(const wxTarEntry
& e
)
516 m_IsModeSet
= e
.m_IsModeSet
;
517 m_UserId
= e
.m_UserId
;
518 m_GroupId
= e
.m_GroupId
;
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
;
534 wxString
wxTarEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
536 bool isDir
= IsDir() && !m_Name
.empty();
538 // optimisations for common (and easy) cases
539 switch (wxFileName::GetFormat(format
)) {
542 wxString
name(isDir
? m_Name
+ wxT("\\") : m_Name
);
543 for (size_t i
= 0; i
< name
.length(); i
++)
544 if (name
[i
] == wxT('/'))
550 return isDir
? m_Name
+ wxT("/") : m_Name
;
559 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
561 fn
.Assign(m_Name
, wxPATH_UNIX
);
563 return fn
.GetFullPath(format
);
566 void wxTarEntry::SetName(const wxString
& name
, wxPathFormat format
)
569 m_Name
= GetInternalName(name
, format
, &isDir
);
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.
578 wxString
wxTarEntry::GetInternalName(const wxString
& name
,
579 wxPathFormat format
/*=wxPATH_NATIVE*/,
580 bool *pIsDir
/*=NULL*/)
584 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
585 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
589 bool isDir
= !internal
.empty() && internal
.Last() == '/';
593 internal
.erase(internal
.length() - 1);
595 while (!internal
.empty() && *internal
.begin() == '/')
596 internal
.erase(0, 1);
597 while (!internal
.empty() && internal
.compare(0, 2, wxT("./")) == 0)
598 internal
.erase(0, 2);
599 if (internal
== wxT(".") || internal
== wxT(".."))
600 internal
= wxEmptyString
;
605 bool wxTarEntry::IsDir() const
607 return m_TypeFlag
== wxTAR_DIRTYPE
;
610 void wxTarEntry::SetIsDir(bool isDir
)
613 m_TypeFlag
= wxTAR_DIRTYPE
;
614 else if (m_TypeFlag
== wxTAR_DIRTYPE
)
615 m_TypeFlag
= wxTAR_REGTYPE
;
618 void wxTarEntry::SetIsReadOnly(bool isReadOnly
)
626 int wxTarEntry::GetMode() const
628 if (m_IsModeSet
|| !IsDir())
631 return m_Mode
| 0111;
635 void wxTarEntry::SetMode(int mode
)
637 m_Mode
= mode
& 07777;
642 /////////////////////////////////////////////////////////////////////////////
645 wxDECLARE_SCOPED_PTR(wxTarEntry
, wxTarEntryPtr_
)
646 wxDEFINE_SCOPED_PTR (wxTarEntry
, wxTarEntryPtr_
)
648 wxTarInputStream::wxTarInputStream(wxInputStream
& stream
,
649 wxMBConv
& conv
/*=wxConvLocal*/)
650 : wxArchiveInputStream(stream
, conv
)
655 wxTarInputStream::wxTarInputStream(wxInputStream
*stream
,
656 wxMBConv
& conv
/*=wxConvLocal*/)
657 : wxArchiveInputStream(stream
, conv
)
662 void wxTarInputStream::Init()
664 m_pos
= wxInvalidOffset
;
666 m_size
= wxInvalidOffset
;
667 m_sumType
= SUM_UNKNOWN
;
668 m_tarType
= TYPE_USTAR
;
669 m_hdr
= new wxTarHeaderBlock
;
671 m_GlobalHeaderRecs
= NULL
;
672 m_lasterror
= m_parent_i_stream
->GetLastError();
675 wxTarInputStream::~wxTarInputStream()
679 delete m_GlobalHeaderRecs
;
682 wxTarEntry
*wxTarInputStream::GetNextEntry()
684 m_lasterror
= ReadHeaders();
689 wxTarEntryPtr_
entry(new wxTarEntry
);
691 entry
->SetMode(GetHeaderNumber(TAR_MODE
));
692 entry
->SetUserId(GetHeaderNumber(TAR_UID
));
693 entry
->SetGroupId(GetHeaderNumber(TAR_UID
));
694 entry
->SetSize(GetHeaderNumber(TAR_SIZE
));
696 entry
->SetOffset(m_offset
);
698 entry
->SetDateTime(GetHeaderDate(wxT("mtime")));
699 entry
->SetAccessTime(GetHeaderDate(wxT("atime")));
700 entry
->SetCreateTime(GetHeaderDate(wxT("ctime")));
702 entry
->SetTypeFlag(*m_hdr
->Get(TAR_TYPEFLAG
));
703 bool isDir
= entry
->IsDir();
705 entry
->SetLinkName(GetHeaderString(TAR_LINKNAME
));
707 if (m_tarType
!= TYPE_OLDTAR
) {
708 entry
->SetUserName(GetHeaderString(TAR_UNAME
));
709 entry
->SetGroupName(GetHeaderString(TAR_GNAME
));
711 entry
->SetDevMajor(GetHeaderNumber(TAR_DEVMAJOR
));
712 entry
->SetDevMinor(GetHeaderNumber(TAR_DEVMINOR
));
715 entry
->SetName(GetHeaderPath(), wxPATH_UNIX
);
720 m_HeaderRecs
->clear();
722 m_size
= GetDataSize(*entry
);
725 return entry
.release();
728 bool wxTarInputStream::OpenEntry(wxTarEntry
& entry
)
730 wxFileOffset offset
= entry
.GetOffset();
732 if (GetLastError() != wxSTREAM_READ_ERROR
733 && m_parent_i_stream
->IsSeekable()
734 && m_parent_i_stream
->SeekI(offset
) == offset
)
737 m_size
= GetDataSize(entry
);
739 m_lasterror
= wxSTREAM_NO_ERROR
;
742 m_lasterror
= wxSTREAM_READ_ERROR
;
747 bool wxTarInputStream::OpenEntry(wxArchiveEntry
& entry
)
749 wxTarEntry
*tarEntry
= wxStaticCast(&entry
, wxTarEntry
);
750 return tarEntry
? OpenEntry(*tarEntry
) : false;
753 bool wxTarInputStream::CloseEntry()
755 if (m_lasterror
== wxSTREAM_READ_ERROR
)
760 wxFileOffset size
= RoundUpSize(m_size
);
761 wxFileOffset remainder
= size
- m_pos
;
763 if (remainder
&& m_parent_i_stream
->IsSeekable()) {
765 if (m_parent_i_stream
->SeekI(remainder
, wxFromCurrent
)
771 const int BUFSIZE
= 8192;
772 wxCharBuffer
buf(BUFSIZE
);
774 while (remainder
> 0 && m_parent_i_stream
->IsOk())
775 remainder
-= m_parent_i_stream
->Read(
776 buf
.data(), wxMin(BUFSIZE
, remainder
)).LastRead();
779 m_pos
= wxInvalidOffset
;
781 m_lasterror
= m_parent_i_stream
->GetLastError();
786 wxStreamError
wxTarInputStream::ReadHeaders()
789 return wxSTREAM_READ_ERROR
;
794 m_hdr
->Read(*m_parent_i_stream
);
795 if (m_parent_i_stream
->Eof())
797 wxLogError(_("incomplete header block in tar"));
799 if (!*m_parent_i_stream
)
800 return wxSTREAM_READ_ERROR
;
801 m_offset
+= TAR_BLOCKSIZE
;
803 // an all-zero header marks the end of the tar
804 if (m_hdr
->IsAllZeros())
807 // the checksum is supposed to be the unsigned sum of the header bytes,
808 // but there have been versions of tar that used the signed sum, so
809 // accept that too, but only if used throughout.
810 wxUint32 chksum
= m_hdr
->GetOctal(TAR_CHKSUM
);
813 if (m_sumType
!= SUM_SIGNED
) {
814 ok
= chksum
== m_hdr
->Sum();
815 if (m_sumType
== SUM_UNKNOWN
)
816 m_sumType
= ok
? SUM_UNSIGNED
: SUM_SIGNED
;
818 if (m_sumType
== SUM_SIGNED
)
819 ok
= chksum
== m_hdr
->Sum(true);
821 wxLogError(_("checksum failure reading tar header block"));
822 return wxSTREAM_READ_ERROR
;
825 if (strcmp(m_hdr
->Get(TAR_MAGIC
), USTAR_MAGIC
) == 0)
826 m_tarType
= TYPE_USTAR
;
827 else if (strcmp(m_hdr
->Get(TAR_MAGIC
), GNU_MAGIC
) == 0 &&
828 strcmp(m_hdr
->Get(TAR_VERSION
), GNU_VERION
) == 0)
829 m_tarType
= TYPE_GNUTAR
;
831 m_tarType
= TYPE_OLDTAR
;
833 if (m_tarType
!= TYPE_USTAR
)
836 switch (*m_hdr
->Get(TAR_TYPEFLAG
)) {
837 case 'g': ReadExtendedHeader(m_GlobalHeaderRecs
); break;
838 case 'x': ReadExtendedHeader(m_HeaderRecs
); break;
839 default: done
= true;
843 return wxSTREAM_NO_ERROR
;
846 wxString
wxTarInputStream::GetExtendedHeader(const wxString
& key
) const
848 wxTarHeaderRecords::iterator it
;
850 // look at normal extended header records first
852 it
= m_HeaderRecs
->find(key
);
853 if (it
!= m_HeaderRecs
->end())
854 return wxString(it
->second
.wc_str(wxConvUTF8
), GetConv());
857 // if not found, look at the global header records
858 if (m_GlobalHeaderRecs
) {
859 it
= m_GlobalHeaderRecs
->find(key
);
860 if (it
!= m_GlobalHeaderRecs
->end())
861 return wxString(it
->second
.wc_str(wxConvUTF8
), GetConv());
864 return wxEmptyString
;
867 wxString
wxTarInputStream::GetHeaderPath() const
871 if ((path
= GetExtendedHeader(wxT("path"))) != wxEmptyString
)
874 path
= wxString(m_hdr
->Get(TAR_NAME
), GetConv());
875 if (m_tarType
!= TYPE_USTAR
)
878 const char *prefix
= m_hdr
->Get(TAR_PREFIX
);
879 return *prefix
? wxString(prefix
, GetConv()) + wxT("/") + path
: path
;
882 wxDateTime
wxTarInputStream::GetHeaderDate(const wxString
& key
) const
886 // try extended header, stored as decimal seconds since the epoch
887 if ((value
= GetExtendedHeader(key
)) != wxEmptyString
) {
889 ll
.Assign(wxAtof(value
) * 1000.0);
893 if (key
== wxT("mtime"))
894 return wxLongLong(m_hdr
->GetOctal(TAR_MTIME
)) * 1000L;
899 wxTarNumber
wxTarInputStream::GetHeaderNumber(int id
) const
903 if ((value
= GetExtendedHeader(m_hdr
->Name(id
))) != wxEmptyString
) {
905 wxString::const_iterator p
= value
.begin();
906 while (*p
== ' ' && p
!= value
.end())
909 n
= n
* 10 + (*p
++ - '0');
912 return m_hdr
->GetOctal(id
);
916 wxString
wxTarInputStream::GetHeaderString(int id
) const
920 if ((value
= GetExtendedHeader(m_hdr
->Name(id
))) != wxEmptyString
)
923 return wxString(m_hdr
->Get(id
), GetConv());
926 // An extended header consists of one or more records, each constructed:
927 // "%d %s=%s\n", <length>, <keyword>, <value>
928 // <length> is the byte length, <keyword> and <value> are UTF-8
930 bool wxTarInputStream::ReadExtendedHeader(wxTarHeaderRecords
*& recs
)
933 recs
= new wxTarHeaderRecords
;
935 // round length up to a whole number of blocks
936 size_t len
= m_hdr
->GetOctal(TAR_SIZE
);
937 size_t size
= RoundUpSize(len
);
939 // read in the whole header since it should be small
940 wxCharBuffer
buf(size
);
941 size_t lastread
= m_parent_i_stream
->Read(buf
.data(), size
).LastRead();
945 m_offset
+= lastread
;
947 size_t recPos
, recSize
;
950 for (recPos
= 0; recPos
< len
&& ok
; recPos
+= recSize
) {
951 char *pRec
= buf
.data() + recPos
;
954 // read the record size (byte count in ascii decimal)
956 while (isdigit((unsigned char) *p
))
957 recSize
= recSize
* 10 + *p
++ - '0';
960 if (recPos
+ recSize
> len
)
962 if (recSize
< p
- pRec
+ (size_t)3 || *p
!= ' '
963 || pRec
[recSize
- 1] != '\012') {
968 // replace the final '\n' with a nul, to terminate value
969 pRec
[recSize
- 1] = 0;
970 // the key is here, following the space
973 // look forward for the '=', the value follows
974 while (*p
&& *p
!= '=')
980 // replace the '=' with a nul, to terminate the key
983 wxString
key(wxConvUTF8
.cMB2WC(pKey
), GetConv());
984 wxString
value(wxConvUTF8
.cMB2WC(p
), GetConv());
986 // an empty value unsets a previously given value
990 (*recs
)[key
] = value
;
993 if (!ok
|| recPos
< len
|| size
!= lastread
) {
994 wxLogWarning(_("invalid data in extended tar header"));
1001 wxFileOffset
wxTarInputStream::OnSysSeek(wxFileOffset pos
, wxSeekMode mode
)
1004 wxLogError(_("tar entry not open"));
1005 m_lasterror
= wxSTREAM_READ_ERROR
;
1008 return wxInvalidOffset
;
1011 case wxFromStart
: break;
1012 case wxFromCurrent
: pos
+= m_pos
; break;
1013 case wxFromEnd
: pos
+= m_size
; break;
1016 if (pos
< 0 || m_parent_i_stream
->SeekI(m_offset
+ pos
) == wxInvalidOffset
)
1017 return wxInvalidOffset
;
1023 size_t wxTarInputStream::OnSysRead(void *buffer
, size_t size
)
1026 wxLogError(_("tar entry not open"));
1027 m_lasterror
= wxSTREAM_READ_ERROR
;
1029 if (!IsOk() || !size
)
1032 if (m_pos
>= m_size
)
1034 else if (m_pos
+ size
> m_size
+ (size_t)0)
1035 size
= m_size
- m_pos
;
1037 size_t lastread
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
1040 if (m_pos
>= m_size
) {
1041 m_lasterror
= wxSTREAM_EOF
;
1042 } else if (!m_parent_i_stream
->IsOk()) {
1043 // any other error will have been reported by the underlying stream
1044 if (m_parent_i_stream
->Eof())
1046 wxLogError(_("unexpected end of file"));
1048 m_lasterror
= wxSTREAM_READ_ERROR
;
1055 /////////////////////////////////////////////////////////////////////////////
1058 wxTarOutputStream::wxTarOutputStream(wxOutputStream
& stream
,
1059 wxTarFormat format
/*=wxTAR_PAX*/,
1060 wxMBConv
& conv
/*=wxConvLocal*/)
1061 : wxArchiveOutputStream(stream
, conv
)
1066 wxTarOutputStream::wxTarOutputStream(wxOutputStream
*stream
,
1067 wxTarFormat format
/*=wxTAR_PAX*/,
1068 wxMBConv
& conv
/*=wxConvLocal*/)
1069 : wxArchiveOutputStream(stream
, conv
)
1074 void wxTarOutputStream::Init(wxTarFormat format
)
1076 m_pos
= wxInvalidOffset
;
1077 m_maxpos
= wxInvalidOffset
;
1078 m_size
= wxInvalidOffset
;
1079 m_headpos
= wxInvalidOffset
;
1080 m_datapos
= wxInvalidOffset
;
1081 m_tarstart
= wxInvalidOffset
;
1083 m_pax
= format
== wxTAR_PAX
;
1084 m_BlockingFactor
= m_pax
? 10 : 20;
1087 m_hdr
= new wxTarHeaderBlock
;
1089 m_extendedHdr
= NULL
;
1091 m_lasterror
= m_parent_o_stream
->GetLastError();
1092 m_endrecWritten
= false;
1095 wxTarOutputStream::~wxTarOutputStream()
1100 delete [] m_extendedHdr
;
1103 bool wxTarOutputStream::PutNextEntry(wxTarEntry
*entry
)
1105 wxTarEntryPtr_
e(entry
);
1112 m_tarstart
= m_parent_o_stream
->TellO();
1115 if (m_tarstart
!= wxInvalidOffset
)
1116 m_headpos
= m_tarstart
+ m_tarsize
;
1118 if (WriteHeaders(*e
)) {
1121 m_size
= GetDataSize(*e
);
1122 if (m_tarstart
!= wxInvalidOffset
)
1123 m_datapos
= m_tarstart
+ m_tarsize
;
1125 // types that are not allowd any data
1126 const char nodata
[] = {
1127 wxTAR_LNKTYPE
, wxTAR_SYMTYPE
, wxTAR_CHRTYPE
, wxTAR_BLKTYPE
,
1128 wxTAR_DIRTYPE
, wxTAR_FIFOTYPE
, 0
1130 int typeflag
= e
->GetTypeFlag();
1132 // pax does now allow data for wxTAR_LNKTYPE
1133 if (!m_pax
|| typeflag
!= wxTAR_LNKTYPE
)
1134 if (strchr(nodata
, typeflag
) != NULL
)
1141 bool wxTarOutputStream::PutNextEntry(const wxString
& name
,
1142 const wxDateTime
& dt
,
1145 return PutNextEntry(new wxTarEntry(name
, dt
, size
));
1148 bool wxTarOutputStream::PutNextDirEntry(const wxString
& name
,
1149 const wxDateTime
& dt
)
1151 wxTarEntry
*entry
= new wxTarEntry(name
, dt
);
1153 return PutNextEntry(entry
);
1156 bool wxTarOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1158 wxTarEntry
*tarEntry
= wxStaticCast(entry
, wxTarEntry
);
1161 return PutNextEntry(tarEntry
);
1164 bool wxTarOutputStream::CopyEntry(wxTarEntry
*entry
,
1165 wxTarInputStream
& inputStream
)
1167 if (PutNextEntry(entry
))
1169 return IsOk() && inputStream
.Eof();
1172 bool wxTarOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1173 wxArchiveInputStream
& inputStream
)
1175 if (PutNextEntry(entry
))
1177 return IsOk() && inputStream
.Eof();
1180 bool wxTarOutputStream::CloseEntry()
1185 if (m_pos
< m_maxpos
) {
1186 wxASSERT(m_parent_o_stream
->IsSeekable());
1187 m_parent_o_stream
->SeekO(m_datapos
+ m_maxpos
);
1188 m_lasterror
= m_parent_o_stream
->GetLastError();
1193 wxFileOffset size
= RoundUpSize(m_pos
);
1195 memset(m_hdr
, 0, size
- m_pos
);
1196 m_parent_o_stream
->Write(m_hdr
, size
- m_pos
);
1197 m_lasterror
= m_parent_o_stream
->GetLastError();
1202 if (IsOk() && m_pos
!= m_size
)
1205 m_pos
= wxInvalidOffset
;
1206 m_maxpos
= wxInvalidOffset
;
1207 m_size
= wxInvalidOffset
;
1208 m_headpos
= wxInvalidOffset
;
1209 m_datapos
= wxInvalidOffset
;
1214 bool wxTarOutputStream::Close()
1216 if (!CloseEntry() || (m_tarsize
== 0 && m_endrecWritten
))
1219 memset(m_hdr
, 0, sizeof(*m_hdr
));
1220 int count
= (RoundUpSize(m_tarsize
+ 2 * TAR_BLOCKSIZE
, m_BlockingFactor
)
1221 - m_tarsize
) / TAR_BLOCKSIZE
;
1223 m_parent_o_stream
->Write(m_hdr
, TAR_BLOCKSIZE
);
1226 m_tarstart
= wxInvalidOffset
;
1227 m_lasterror
= m_parent_o_stream
->GetLastError();
1228 m_endrecWritten
= true;
1232 bool wxTarOutputStream::WriteHeaders(wxTarEntry
& entry
)
1234 memset(m_hdr
, 0, sizeof(*m_hdr
));
1236 SetHeaderPath(entry
.GetName(wxPATH_UNIX
));
1238 SetHeaderNumber(TAR_MODE
, entry
.GetMode());
1239 SetHeaderNumber(TAR_UID
, entry
.GetUserId());
1240 SetHeaderNumber(TAR_GID
, entry
.GetGroupId());
1242 if (entry
.GetSize() == wxInvalidOffset
)
1244 m_large
= !SetHeaderNumber(TAR_SIZE
, entry
.GetSize());
1246 SetHeaderDate(wxT("mtime"), entry
.GetDateTime());
1247 if (entry
.GetAccessTime().IsValid())
1248 SetHeaderDate(wxT("atime"), entry
.GetAccessTime());
1249 if (entry
.GetCreateTime().IsValid())
1250 SetHeaderDate(wxT("ctime"), entry
.GetCreateTime());
1252 *m_hdr
->Get(TAR_TYPEFLAG
) = char(entry
.GetTypeFlag());
1254 strcpy(m_hdr
->Get(TAR_MAGIC
), USTAR_MAGIC
);
1255 strcpy(m_hdr
->Get(TAR_VERSION
), USTAR_VERSION
);
1257 SetHeaderString(TAR_LINKNAME
, entry
.GetLinkName());
1258 SetHeaderString(TAR_UNAME
, entry
.GetUserName());
1259 SetHeaderString(TAR_GNAME
, entry
.GetGroupName());
1261 if (~entry
.GetDevMajor())
1262 SetHeaderNumber(TAR_DEVMAJOR
, entry
.GetDevMajor());
1263 if (~entry
.GetDevMinor())
1264 SetHeaderNumber(TAR_DEVMINOR
, entry
.GetDevMinor());
1266 m_chksum
= m_hdr
->Sum();
1267 m_hdr
->SetOctal(TAR_CHKSUM
, m_chksum
);
1269 m_chksum
-= m_hdr
->SumField(TAR_SIZE
);
1271 // The main header is now fully prepared so we know what extended headers
1272 // (if any) will be needed. Output any extended headers before writing
1274 if (m_extendedHdr
&& *m_extendedHdr
) {
1276 // the extended headers are written to the tar as a file entry,
1277 // so prepare a regular header block for the pseudo-file.
1279 m_hdr2
= new wxTarHeaderBlock
;
1280 memset(m_hdr2
, 0, sizeof(*m_hdr2
));
1282 // an old tar that doesn't understand extended headers will
1283 // extract it as a file, so give these fields reasonable values
1284 // so that the user will have access to read and remove it.
1285 m_hdr2
->SetPath(PaxHeaderPath(wxT("%d/PaxHeaders.%p/%f"),
1286 entry
.GetName(wxPATH_UNIX
)), GetConv());
1287 m_hdr2
->SetOctal(TAR_MODE
, 0600);
1288 strcpy(m_hdr2
->Get(TAR_UID
), m_hdr
->Get(TAR_UID
));
1289 strcpy(m_hdr2
->Get(TAR_GID
), m_hdr
->Get(TAR_GID
));
1290 size_t length
= strlen(m_extendedHdr
);
1291 m_hdr2
->SetOctal(TAR_SIZE
, length
);
1292 strcpy(m_hdr2
->Get(TAR_MTIME
), m_hdr
->Get(TAR_MTIME
));
1293 *m_hdr2
->Get(TAR_TYPEFLAG
) = 'x';
1294 strcpy(m_hdr2
->Get(TAR_MAGIC
), USTAR_MAGIC
);
1295 strcpy(m_hdr2
->Get(TAR_VERSION
), USTAR_VERSION
);
1296 strcpy(m_hdr2
->Get(TAR_UNAME
), m_hdr
->Get(TAR_UNAME
));
1297 strcpy(m_hdr2
->Get(TAR_GNAME
), m_hdr
->Get(TAR_GNAME
));
1299 m_hdr2
->SetOctal(TAR_CHKSUM
, m_hdr2
->Sum());
1301 m_hdr2
->Write(*m_parent_o_stream
);
1302 m_tarsize
+= TAR_BLOCKSIZE
;
1304 size_t rounded
= RoundUpSize(length
);
1305 memset(m_extendedHdr
+ length
, 0, rounded
- length
);
1306 m_parent_o_stream
->Write(m_extendedHdr
, rounded
);
1307 m_tarsize
+= rounded
;
1311 // update m_headpos which is used to seek back to fix up the file
1312 // length if it is not known in advance
1313 if (m_tarstart
!= wxInvalidOffset
)
1314 m_headpos
= m_tarstart
+ m_tarsize
;
1317 // if don't have extended headers just report error
1318 if (!m_badfit
.empty()) {
1320 wxLogWarning(_("%s did not fit the tar header for entry '%s'"),
1321 m_badfit
.c_str(), entry
.GetName().c_str());
1325 m_hdr
->Write(*m_parent_o_stream
);
1326 m_tarsize
+= TAR_BLOCKSIZE
;
1327 m_lasterror
= m_parent_o_stream
->GetLastError();
1332 wxString
wxTarOutputStream::PaxHeaderPath(const wxString
& format
,
1333 const wxString
& path
)
1335 wxString d
= path
.BeforeLast(wxT('/'));
1336 wxString f
= path
.AfterLast(wxT('/'));
1342 ret
.reserve(format
.length() + path
.length() + 16);
1348 end
= format
.find('%', begin
);
1349 if (end
== wxString::npos
|| end
+ 1 >= format
.length())
1351 ret
<< format
.substr(begin
, end
- begin
);
1352 switch ( format
[end
+ 1].GetValue() ) {
1353 case 'd': ret
<< d
; break;
1354 case 'f': ret
<< f
; break;
1355 case 'p': ret
<< wxGetProcessId(); break;
1356 case '%': ret
<< wxT("%"); break;
1361 ret
<< format
.substr(begin
);
1366 bool wxTarOutputStream::ModifyHeader()
1368 wxFileOffset originalPos
= wxInvalidOffset
;
1369 wxFileOffset sizePos
= wxInvalidOffset
;
1371 if (!m_large
&& m_headpos
!= wxInvalidOffset
1372 && m_parent_o_stream
->IsSeekable())
1375 originalPos
= m_parent_o_stream
->TellO();
1376 if (originalPos
!= wxInvalidOffset
)
1378 m_parent_o_stream
->SeekO(m_headpos
+ m_hdr
->Offset(TAR_SIZE
));
1381 if (sizePos
== wxInvalidOffset
|| !m_hdr
->SetOctal(TAR_SIZE
, m_pos
)) {
1382 wxLogError(_("incorrect size given for tar entry"));
1383 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1387 m_chksum
+= m_hdr
->SumField(TAR_SIZE
);
1388 m_hdr
->SetOctal(TAR_CHKSUM
, m_chksum
);
1389 wxFileOffset sumPos
= m_headpos
+ m_hdr
->Offset(TAR_CHKSUM
);
1392 m_hdr
->WriteField(*m_parent_o_stream
, TAR_SIZE
) &&
1393 m_parent_o_stream
->SeekO(sumPos
) == sumPos
&&
1394 m_hdr
->WriteField(*m_parent_o_stream
, TAR_CHKSUM
) &&
1395 m_parent_o_stream
->SeekO(originalPos
) == originalPos
;
1398 void wxTarOutputStream::SetHeaderPath(const wxString
& name
)
1400 if (!m_hdr
->SetPath(name
, GetConv()) || (m_pax
&& !name
.IsAscii()))
1401 SetExtendedHeader(wxT("path"), name
);
1404 bool wxTarOutputStream::SetHeaderNumber(int id
, wxTarNumber n
)
1406 if (m_hdr
->SetOctal(id
, n
)) {
1409 SetExtendedHeader(m_hdr
->Name(id
), wxLongLong(n
).ToString());
1414 void wxTarOutputStream::SetHeaderString(int id
, const wxString
& str
)
1416 strncpy(m_hdr
->Get(id
), str
.mb_str(GetConv()), m_hdr
->Len(id
));
1417 if (str
.length() > m_hdr
->Len(id
))
1418 SetExtendedHeader(m_hdr
->Name(id
), str
);
1421 void wxTarOutputStream::SetHeaderDate(const wxString
& key
,
1422 const wxDateTime
& datetime
)
1424 wxLongLong ll
= datetime
.IsValid() ? datetime
.GetValue() : wxLongLong(0);
1425 wxLongLong secs
= ll
/ 1000L;
1427 if (key
!= wxT("mtime")
1428 || !m_hdr
->SetOctal(TAR_MTIME
, wxTarNumber(secs
.GetValue()))
1429 || secs
<= 0 || secs
>= 0x7fffffff)
1432 if (ll
>= LONG_MIN
&& ll
<= LONG_MAX
) {
1433 str
.Printf(wxT("%g"), ll
.ToLong() / 1000.0);
1435 str
= ll
.ToString();
1436 str
.insert(str
.end() - 3, '.');
1438 SetExtendedHeader(key
, str
);
1442 void wxTarOutputStream::SetExtendedHeader(const wxString
& key
,
1443 const wxString
& value
)
1447 const wxCharBuffer utf_key
= key
.utf8_str();
1448 const wxCharBuffer utf_value
= value
.utf8_str();
1450 const wxWX2WCbuf wide_key
= key
.wc_str(GetConv());
1451 const wxCharBuffer utf_key
= wxConvUTF8
.cWC2MB(wide_key
);
1453 const wxWX2WCbuf wide_value
= value
.wc_str(GetConv());
1454 const wxCharBuffer utf_value
= wxConvUTF8
.cWC2MB(wide_value
);
1455 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
1457 // a small buffer to format the length field in
1459 // length of "99<space><key>=<value>\n"
1460 unsigned long length
= strlen(utf_value
) + strlen(utf_key
) + 5;
1461 sprintf(buf
, "%lu", length
);
1462 // the length includes itself
1463 size_t lenlen
= strlen(buf
);
1465 length
+= lenlen
- 2;
1466 sprintf(buf
, "%lu", length
);
1467 if (strlen(buf
) > lenlen
)
1468 sprintf(buf
, "%lu", ++length
);
1471 // reallocate m_extendedHdr if it's not big enough
1472 if (m_extendedSize
< length
) {
1473 size_t rounded
= RoundUpSize(length
);
1474 m_extendedSize
<<= 1;
1475 if (rounded
> m_extendedSize
)
1476 m_extendedSize
= rounded
;
1477 char *oldHdr
= m_extendedHdr
;
1478 m_extendedHdr
= new char[m_extendedSize
];
1480 strcpy(m_extendedHdr
, oldHdr
);
1487 // append the new record
1488 char *append
= strchr(m_extendedHdr
, 0);
1489 sprintf(append
, "%s %s=%s\012", buf
,
1490 (const char*)utf_key
, (const char*)utf_value
);
1493 // if not pax then make a list of fields to report as errors
1494 if (!m_badfit
.empty())
1495 m_badfit
+= wxT(", ");
1500 void wxTarOutputStream::Sync()
1502 m_parent_o_stream
->Sync();
1505 wxFileOffset
wxTarOutputStream::OnSysSeek(wxFileOffset pos
, wxSeekMode mode
)
1508 wxLogError(_("tar entry not open"));
1509 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1511 if (!IsOk() || m_datapos
== wxInvalidOffset
)
1512 return wxInvalidOffset
;
1515 case wxFromStart
: break;
1516 case wxFromCurrent
: pos
+= m_pos
; break;
1517 case wxFromEnd
: pos
+= m_maxpos
; break;
1520 if (pos
< 0 || m_parent_o_stream
->SeekO(m_datapos
+ pos
) == wxInvalidOffset
)
1521 return wxInvalidOffset
;
1527 size_t wxTarOutputStream::OnSysWrite(const void *buffer
, size_t size
)
1530 wxLogError(_("tar entry not open"));
1531 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1533 if (!IsOk() || !size
)
1536 size_t lastwrite
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
1538 if (m_pos
> m_maxpos
)
1541 if (lastwrite
!= size
)
1542 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1547 #endif // wxUSE_TARSTREAM