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
[] = { _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
};
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 { _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
}
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
+ _T("\\") : m_Name
);
543 for (size_t i
= 0; i
< name
.length(); i
++)
544 if (name
[i
] == _T('/'))
550 return isDir
? m_Name
+ _T("/") : 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, _T("./")) == 0)
598 internal
.erase(0, 2);
599 if (internal
== _T(".") || internal
== _T(".."))
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(_T("mtime")));
699 entry
->SetAccessTime(GetHeaderDate(_T("atime")));
700 entry
->SetCreateTime(GetHeaderDate(_T("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())
796 wxLogError(_("incomplete header block in tar"));
797 if (!*m_parent_i_stream
)
798 return wxSTREAM_READ_ERROR
;
799 m_offset
+= TAR_BLOCKSIZE
;
801 // an all-zero header marks the end of the tar
802 if (m_hdr
->IsAllZeros())
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
);
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
;
816 if (m_sumType
== SUM_SIGNED
)
817 ok
= chksum
== m_hdr
->Sum(true);
819 wxLogError(_("checksum failure reading tar header block"));
820 return wxSTREAM_READ_ERROR
;
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
;
829 m_tarType
= TYPE_OLDTAR
;
831 if (m_tarType
!= TYPE_USTAR
)
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;
841 return wxSTREAM_NO_ERROR
;
844 wxString
wxTarInputStream::GetExtendedHeader(const wxString
& key
) const
846 wxTarHeaderRecords::iterator it
;
848 // look at normal extended header records first
850 it
= m_HeaderRecs
->find(key
);
851 if (it
!= m_HeaderRecs
->end())
852 return wxString(it
->second
.wc_str(wxConvUTF8
), GetConv());
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());
862 return wxEmptyString
;
865 wxString
wxTarInputStream::GetHeaderPath() const
869 if ((path
= GetExtendedHeader(_T("path"))) != wxEmptyString
)
872 path
= wxString(m_hdr
->Get(TAR_NAME
), GetConv());
873 if (m_tarType
!= TYPE_USTAR
)
876 const char *prefix
= m_hdr
->Get(TAR_PREFIX
);
877 return *prefix
? wxString(prefix
, GetConv()) + _T("/") + path
: path
;
880 wxDateTime
wxTarInputStream::GetHeaderDate(const wxString
& key
) const
884 // try extended header, stored as decimal seconds since the epoch
885 if ((value
= GetExtendedHeader(key
)) != wxEmptyString
) {
887 ll
.Assign(wxAtof(value
) * 1000.0);
891 if (key
== _T("mtime"))
892 return wxLongLong(m_hdr
->GetOctal(TAR_MTIME
)) * 1000L;
897 wxTarNumber
wxTarInputStream::GetHeaderNumber(int id
) const
901 if ((value
= GetExtendedHeader(m_hdr
->Name(id
))) != wxEmptyString
) {
903 wxString::const_iterator p
= value
.begin();
904 while (*p
== ' ' && p
!= value
.end())
907 n
= n
* 10 + (*p
++ - '0');
910 return m_hdr
->GetOctal(id
);
914 wxString
wxTarInputStream::GetHeaderString(int id
) const
918 if ((value
= GetExtendedHeader(m_hdr
->Name(id
))) != wxEmptyString
)
921 return wxString(m_hdr
->Get(id
), GetConv());
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
928 bool wxTarInputStream::ReadExtendedHeader(wxTarHeaderRecords
*& recs
)
931 recs
= new wxTarHeaderRecords
;
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
);
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();
943 m_offset
+= lastread
;
945 size_t recPos
, recSize
;
948 for (recPos
= 0; recPos
< len
&& ok
; recPos
+= recSize
) {
949 char *pRec
= buf
.data() + recPos
;
952 // read the record size (byte count in ascii decimal)
954 while (isdigit((unsigned char) *p
))
955 recSize
= recSize
* 10 + *p
++ - '0';
958 if (recPos
+ recSize
> len
)
960 if (recSize
< p
- pRec
+ (size_t)3 || *p
!= ' '
961 || pRec
[recSize
- 1] != '\012') {
966 // replace the final '\n' with a nul, to terminate value
967 pRec
[recSize
- 1] = 0;
968 // the key is here, following the space
971 // look forward for the '=', the value follows
972 while (*p
&& *p
!= '=')
978 // replace the '=' with a nul, to terminate the key
981 wxString
key(wxConvUTF8
.cMB2WC(pKey
), GetConv());
982 wxString
value(wxConvUTF8
.cMB2WC(p
), GetConv());
984 // an empty value unsets a previously given value
988 (*recs
)[key
] = value
;
991 if (!ok
|| recPos
< len
|| size
!= lastread
) {
992 wxLogWarning(_("invalid data in extended tar header"));
999 wxFileOffset
wxTarInputStream::OnSysSeek(wxFileOffset pos
, wxSeekMode mode
)
1002 wxLogError(_("tar entry not open"));
1003 m_lasterror
= wxSTREAM_READ_ERROR
;
1006 return wxInvalidOffset
;
1009 case wxFromStart
: break;
1010 case wxFromCurrent
: pos
+= m_pos
; break;
1011 case wxFromEnd
: pos
+= m_size
; break;
1014 if (pos
< 0 || m_parent_i_stream
->SeekI(m_offset
+ pos
) == wxInvalidOffset
)
1015 return wxInvalidOffset
;
1021 size_t wxTarInputStream::OnSysRead(void *buffer
, size_t size
)
1024 wxLogError(_("tar entry not open"));
1025 m_lasterror
= wxSTREAM_READ_ERROR
;
1027 if (!IsOk() || !size
)
1030 if (m_pos
>= m_size
)
1032 else if (m_pos
+ size
> m_size
+ (size_t)0)
1033 size
= m_size
- m_pos
;
1035 size_t lastread
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
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
;
1051 /////////////////////////////////////////////////////////////////////////////
1054 wxTarOutputStream::wxTarOutputStream(wxOutputStream
& stream
,
1055 wxTarFormat format
/*=wxTAR_PAX*/,
1056 wxMBConv
& conv
/*=wxConvLocal*/)
1057 : wxArchiveOutputStream(stream
, conv
)
1062 wxTarOutputStream::wxTarOutputStream(wxOutputStream
*stream
,
1063 wxTarFormat format
/*=wxTAR_PAX*/,
1064 wxMBConv
& conv
/*=wxConvLocal*/)
1065 : wxArchiveOutputStream(stream
, conv
)
1070 void wxTarOutputStream::Init(wxTarFormat format
)
1072 m_pos
= wxInvalidOffset
;
1073 m_maxpos
= wxInvalidOffset
;
1074 m_size
= wxInvalidOffset
;
1075 m_headpos
= wxInvalidOffset
;
1076 m_datapos
= wxInvalidOffset
;
1077 m_tarstart
= wxInvalidOffset
;
1079 m_pax
= format
== wxTAR_PAX
;
1080 m_BlockingFactor
= m_pax
? 10 : 20;
1083 m_hdr
= new wxTarHeaderBlock
;
1085 m_extendedHdr
= NULL
;
1087 m_lasterror
= m_parent_o_stream
->GetLastError();
1088 m_endrecWritten
= false;
1091 wxTarOutputStream::~wxTarOutputStream()
1096 delete [] m_extendedHdr
;
1099 bool wxTarOutputStream::PutNextEntry(wxTarEntry
*entry
)
1101 wxTarEntryPtr_
e(entry
);
1108 m_tarstart
= m_parent_o_stream
->TellO();
1111 if (m_tarstart
!= wxInvalidOffset
)
1112 m_headpos
= m_tarstart
+ m_tarsize
;
1114 if (WriteHeaders(*e
)) {
1117 m_size
= GetDataSize(*e
);
1118 if (m_tarstart
!= wxInvalidOffset
)
1119 m_datapos
= m_tarstart
+ m_tarsize
;
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
1126 int typeflag
= e
->GetTypeFlag();
1128 // pax does now allow data for wxTAR_LNKTYPE
1129 if (!m_pax
|| typeflag
!= wxTAR_LNKTYPE
)
1130 if (strchr(nodata
, typeflag
) != NULL
)
1137 bool wxTarOutputStream::PutNextEntry(const wxString
& name
,
1138 const wxDateTime
& dt
,
1141 return PutNextEntry(new wxTarEntry(name
, dt
, size
));
1144 bool wxTarOutputStream::PutNextDirEntry(const wxString
& name
,
1145 const wxDateTime
& dt
)
1147 wxTarEntry
*entry
= new wxTarEntry(name
, dt
);
1149 return PutNextEntry(entry
);
1152 bool wxTarOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1154 wxTarEntry
*tarEntry
= wxStaticCast(entry
, wxTarEntry
);
1157 return PutNextEntry(tarEntry
);
1160 bool wxTarOutputStream::CopyEntry(wxTarEntry
*entry
,
1161 wxTarInputStream
& inputStream
)
1163 if (PutNextEntry(entry
))
1165 return IsOk() && inputStream
.Eof();
1168 bool wxTarOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1169 wxArchiveInputStream
& inputStream
)
1171 if (PutNextEntry(entry
))
1173 return IsOk() && inputStream
.Eof();
1176 bool wxTarOutputStream::CloseEntry()
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();
1189 wxFileOffset size
= RoundUpSize(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();
1198 if (IsOk() && m_pos
!= m_size
)
1201 m_pos
= wxInvalidOffset
;
1202 m_maxpos
= wxInvalidOffset
;
1203 m_size
= wxInvalidOffset
;
1204 m_headpos
= wxInvalidOffset
;
1205 m_datapos
= wxInvalidOffset
;
1210 bool wxTarOutputStream::Close()
1212 if (!CloseEntry() || (m_tarsize
== 0 && m_endrecWritten
))
1215 memset(m_hdr
, 0, sizeof(*m_hdr
));
1216 int count
= (RoundUpSize(m_tarsize
+ 2 * TAR_BLOCKSIZE
, m_BlockingFactor
)
1217 - m_tarsize
) / TAR_BLOCKSIZE
;
1219 m_parent_o_stream
->Write(m_hdr
, TAR_BLOCKSIZE
);
1222 m_tarstart
= wxInvalidOffset
;
1223 m_lasterror
= m_parent_o_stream
->GetLastError();
1224 m_endrecWritten
= true;
1228 bool wxTarOutputStream::WriteHeaders(wxTarEntry
& entry
)
1230 memset(m_hdr
, 0, sizeof(*m_hdr
));
1232 SetHeaderPath(entry
.GetName(wxPATH_UNIX
));
1234 SetHeaderNumber(TAR_MODE
, entry
.GetMode());
1235 SetHeaderNumber(TAR_UID
, entry
.GetUserId());
1236 SetHeaderNumber(TAR_GID
, entry
.GetGroupId());
1238 if (entry
.GetSize() == wxInvalidOffset
)
1240 m_large
= !SetHeaderNumber(TAR_SIZE
, entry
.GetSize());
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());
1248 *m_hdr
->Get(TAR_TYPEFLAG
) = char(entry
.GetTypeFlag());
1250 strcpy(m_hdr
->Get(TAR_MAGIC
), USTAR_MAGIC
);
1251 strcpy(m_hdr
->Get(TAR_VERSION
), USTAR_VERSION
);
1253 SetHeaderString(TAR_LINKNAME
, entry
.GetLinkName());
1254 SetHeaderString(TAR_UNAME
, entry
.GetUserName());
1255 SetHeaderString(TAR_GNAME
, entry
.GetGroupName());
1257 if (~entry
.GetDevMajor())
1258 SetHeaderNumber(TAR_DEVMAJOR
, entry
.GetDevMajor());
1259 if (~entry
.GetDevMinor())
1260 SetHeaderNumber(TAR_DEVMINOR
, entry
.GetDevMinor());
1262 m_chksum
= m_hdr
->Sum();
1263 m_hdr
->SetOctal(TAR_CHKSUM
, m_chksum
);
1265 m_chksum
-= m_hdr
->SumField(TAR_SIZE
);
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
1270 if (m_extendedHdr
&& *m_extendedHdr
) {
1272 // the extended headers are written to the tar as a file entry,
1273 // so prepare a regular header block for the pseudo-file.
1275 m_hdr2
= new wxTarHeaderBlock
;
1276 memset(m_hdr2
, 0, sizeof(*m_hdr2
));
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
));
1295 m_hdr2
->SetOctal(TAR_CHKSUM
, m_hdr2
->Sum());
1297 m_hdr2
->Write(*m_parent_o_stream
);
1298 m_tarsize
+= TAR_BLOCKSIZE
;
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
;
1308 // if don't have extended headers just report error
1309 if (!m_badfit
.empty()) {
1311 wxLogWarning(_("%s did not fit the tar header for entry '%s'"),
1312 m_badfit
.c_str(), entry
.GetName().c_str());
1316 m_hdr
->Write(*m_parent_o_stream
);
1317 m_tarsize
+= TAR_BLOCKSIZE
;
1318 m_lasterror
= m_parent_o_stream
->GetLastError();
1323 wxString
wxTarOutputStream::PaxHeaderPath(const wxString
& format
,
1324 const wxString
& path
)
1326 wxString d
= path
.BeforeLast(_T('/'));
1327 wxString f
= path
.AfterLast(_T('/'));
1333 ret
.reserve(format
.length() + path
.length() + 16);
1339 end
= format
.find('%', begin
);
1340 if (end
== wxString::npos
|| end
+ 1 >= format
.length())
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;
1352 ret
<< format
.substr(begin
);
1357 bool wxTarOutputStream::ModifyHeader()
1359 wxFileOffset originalPos
= wxInvalidOffset
;
1360 wxFileOffset sizePos
= wxInvalidOffset
;
1362 if (!m_large
&& m_headpos
!= wxInvalidOffset
1363 && m_parent_o_stream
->IsSeekable())
1366 originalPos
= m_parent_o_stream
->TellO();
1367 if (originalPos
!= wxInvalidOffset
)
1369 m_parent_o_stream
->SeekO(m_headpos
+ m_hdr
->Offset(TAR_SIZE
));
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
;
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
);
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
;
1389 void wxTarOutputStream::SetHeaderPath(const wxString
& name
)
1391 if (!m_hdr
->SetPath(name
, GetConv()) || (m_pax
&& !name
.IsAscii()))
1392 SetExtendedHeader(_T("path"), name
);
1395 bool wxTarOutputStream::SetHeaderNumber(int id
, wxTarNumber n
)
1397 if (m_hdr
->SetOctal(id
, n
)) {
1400 SetExtendedHeader(m_hdr
->Name(id
), wxLongLong(n
).ToString());
1405 void wxTarOutputStream::SetHeaderString(int id
, const wxString
& str
)
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
);
1412 void wxTarOutputStream::SetHeaderDate(const wxString
& key
,
1413 const wxDateTime
& datetime
)
1415 wxLongLong ll
= datetime
.IsValid() ? datetime
.GetValue() : wxLongLong(0);
1416 wxLongLong secs
= ll
/ 1000L;
1418 if (key
!= _T("mtime")
1419 || !m_hdr
->SetOctal(TAR_MTIME
, wxTarNumber(secs
.GetValue()))
1420 || secs
<= 0 || secs
>= 0x7fffffff)
1423 if (ll
>= LONG_MIN
&& ll
<= LONG_MAX
) {
1424 str
.Printf(_T("%g"), ll
.ToLong() / 1000.0);
1426 str
= ll
.ToString();
1427 str
.insert(str
.end() - 3, '.');
1429 SetExtendedHeader(key
, str
);
1433 void wxTarOutputStream::SetExtendedHeader(const wxString
& key
,
1434 const wxString
& value
)
1438 const wxCharBuffer utf_key
= key
.utf8_str();
1439 const wxCharBuffer utf_value
= value
.utf8_str();
1441 const wxWX2WCbuf wide_key
= key
.wc_str(GetConv());
1442 const wxCharBuffer utf_key
= wxConvUTF8
.cWC2MB(wide_key
);
1444 const wxWX2WCbuf wide_value
= value
.wc_str(GetConv());
1445 const wxCharBuffer utf_value
= wxConvUTF8
.cWC2MB(wide_value
);
1446 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
1448 // a small buffer to format the length field in
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
);
1456 length
+= lenlen
- 2;
1457 sprintf(buf
, "%lu", length
);
1458 if (strlen(buf
) > lenlen
)
1459 sprintf(buf
, "%lu", ++length
);
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
];
1471 strcpy(m_extendedHdr
, oldHdr
);
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
);
1484 // if not pax then make a list of fields to report as errors
1485 if (!m_badfit
.empty())
1486 m_badfit
+= _T(", ");
1491 void wxTarOutputStream::Sync()
1493 m_parent_o_stream
->Sync();
1496 wxFileOffset
wxTarOutputStream::OnSysSeek(wxFileOffset pos
, wxSeekMode mode
)
1499 wxLogError(_("tar entry not open"));
1500 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1502 if (!IsOk() || m_datapos
== wxInvalidOffset
)
1503 return wxInvalidOffset
;
1506 case wxFromStart
: break;
1507 case wxFromCurrent
: pos
+= m_pos
; break;
1508 case wxFromEnd
: pos
+= m_maxpos
; break;
1511 if (pos
< 0 || m_parent_o_stream
->SeekO(m_datapos
+ pos
) == wxInvalidOffset
)
1512 return wxInvalidOffset
;
1518 size_t wxTarOutputStream::OnSysWrite(const void *buffer
, size_t size
)
1521 wxLogError(_("tar entry not open"));
1522 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1524 if (!IsOk() || !size
)
1527 size_t lastwrite
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
1529 if (m_pos
> m_maxpos
)
1532 if (lastwrite
!= size
)
1533 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1538 #endif // wxUSE_TARSTREAM