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/ptr_scpd.h"
30 #include "wx/filename.h"
39 /////////////////////////////////////////////////////////////////////////////
76 TYPE_OLDTAR
, // fields after TAR_LINKNAME are invalid
77 TYPE_GNUTAR
, // all fields except TAR_PREFIX are valid
78 TYPE_USTAR
// all fields are valid
82 static const char *USTAR_MAGIC
= "ustar";
83 static const char *USTAR_VERSION
= "00";
84 static const char *GNU_MAGIC
= "ustar ";
85 static const char *GNU_VERION
= " ";
87 IMPLEMENT_DYNAMIC_CLASS(wxTarEntry
, wxArchiveEntry
)
88 IMPLEMENT_DYNAMIC_CLASS(wxTarClassFactory
, wxArchiveClassFactory
)
91 /////////////////////////////////////////////////////////////////////////////
94 static wxTarClassFactory g_wxTarClassFactory
;
96 wxTarClassFactory::wxTarClassFactory()
98 if (this == &g_wxTarClassFactory
)
102 const wxChar
* const *
103 wxTarClassFactory::GetProtocols(wxStreamProtocolType type
) const
105 static const wxChar
*protocols
[] = { _T("tar"), NULL
};
106 static const wxChar
*mimetypes
[] = { _T("application/x-tar"), NULL
};
107 static const wxChar
*fileexts
[] = { _T(".tar"), NULL
};
108 static const wxChar
*empty
[] = { NULL
};
111 case wxSTREAM_PROTOCOL
: return protocols
;
112 case wxSTREAM_MIMETYPE
: return mimetypes
;
113 case wxSTREAM_FILEEXT
: return fileexts
;
114 default: return empty
;
119 /////////////////////////////////////////////////////////////////////////////
122 typedef wxFileOffset wxTarNumber
;
124 struct wxTarField
{ const wxChar
*name
; int pos
; };
126 class wxTarHeaderBlock
130 { memset(data
, 0, sizeof(data
)); }
131 wxTarHeaderBlock(const wxTarHeaderBlock
& hb
)
132 { memcpy(data
, hb
.data
, sizeof(data
)); }
134 bool Read(wxInputStream
& in
);
135 bool Write(wxOutputStream
& out
);
136 inline bool WriteField(wxOutputStream
& out
, int id
);
138 bool IsAllZeros() const;
139 wxUint32
Sum(bool SignedSum
= false);
140 wxUint32
SumField(int id
);
142 char *Get(int id
) { return data
+ fields
[id
].pos
+ id
; }
143 static size_t Len(int id
) { return fields
[id
+ 1].pos
- fields
[id
].pos
; }
144 static const wxChar
*Name(int id
) { return fields
[id
].name
; }
145 static size_t Offset(int id
) { return fields
[id
].pos
; }
147 bool SetOctal(int id
, wxTarNumber n
);
148 wxTarNumber
GetOctal(int id
);
149 bool SetPath(const wxString
& name
, wxMBConv
& conv
);
152 char data
[TAR_BLOCKSIZE
+ TAR_NUMFIELDS
];
153 static const wxTarField fields
[];
157 wxDEFINE_SCOPED_PTR_TYPE(wxTarHeaderBlock
)
159 // A table giving the field names and offsets in a tar header block
160 const wxTarField
wxTarHeaderBlock::fields
[] =
162 { _T("name"), 0 }, // 100
163 { _T("mode"), 100 }, // 8
164 { _T("uid"), 108 }, // 8
165 { _T("gid"), 116 }, // 8
166 { _T("size"), 124 }, // 12
167 { _T("mtime"), 136 }, // 12
168 { _T("chksum"), 148 }, // 8
169 { _T("typeflag"), 156 }, // 1
170 { _T("linkname"), 157 }, // 100
171 { _T("magic"), 257 }, // 6
172 { _T("version"), 263 }, // 2
173 { _T("uname"), 265 }, // 32
174 { _T("gname"), 297 }, // 32
175 { _T("devmajor"), 329 }, // 8
176 { _T("devminor"), 337 }, // 8
177 { _T("prefix"), 345 }, // 155
178 { _T("unused"), 500 }, // 12
179 { NULL
, TAR_BLOCKSIZE
}
182 void wxTarHeaderBlock::check()
185 wxCOMPILE_TIME_ASSERT(
186 WXSIZEOF(fields
) == TAR_NUMFIELDS
+ 1,
187 Wrong_number_of_elements_in_fields_table
192 bool wxTarHeaderBlock::IsAllZeros() const
194 const char *p
= data
;
195 for (size_t i
= 0; i
< sizeof(data
); i
++)
201 wxUint32
wxTarHeaderBlock::Sum(bool SignedSum
/*=false*/)
203 // the chksum field itself should be blanks during the calculation
204 memset(Get(TAR_CHKSUM
), ' ', Len(TAR_CHKSUM
));
205 const char *p
= data
;
209 for (size_t i
= 0; i
< sizeof(data
); i
++)
210 n
+= (signed char)p
[i
];
212 for (size_t i
= 0; i
< sizeof(data
); i
++)
213 n
+= (unsigned char)p
[i
];
218 wxUint32
wxTarHeaderBlock::SumField(int id
)
220 unsigned char *p
= (unsigned char*)Get(id
);
221 unsigned char *q
= p
+ Len(id
);
230 bool wxTarHeaderBlock::Read(wxInputStream
& in
)
234 for (int id
= 0; id
< TAR_NUMFIELDS
&& ok
; id
++)
235 ok
= in
.Read(Get(id
), Len(id
)).LastRead() == Len(id
);
240 bool wxTarHeaderBlock::Write(wxOutputStream
& out
)
244 for (int id
= 0; id
< TAR_NUMFIELDS
&& ok
; id
++)
245 ok
= WriteField(out
, id
);
250 inline bool wxTarHeaderBlock::WriteField(wxOutputStream
& out
, int id
)
252 return out
.Write(Get(id
), Len(id
)).LastWrite() == Len(id
);
255 wxTarNumber
wxTarHeaderBlock::GetOctal(int id
)
258 const char *p
= Get(id
);
261 while (*p
>= '0' && *p
< '8')
262 n
= (n
<< 3) | (*p
++ - '0');
266 bool wxTarHeaderBlock::SetOctal(int id
, wxTarNumber n
)
268 // set an octal field, return true if the number fits
269 char *field
= Get(id
);
270 char *p
= field
+ Len(id
);
273 *--p
= char('0' + (n
& 7));
279 bool wxTarHeaderBlock::SetPath(const wxString
& name
, wxMBConv
& conv
)
281 bool badconv
= false;
284 wxCharBuffer nameBuf
= name
.mb_str(conv
);
286 // if the conversion fails make an approximation
289 size_t len
= name
.length();
290 wxCharBuffer
approx(len
);
291 for (size_t i
= 0; i
< len
; i
++)
292 approx
.data()[i
] = name
[i
] & ~0x7F ? '_' : name
[i
];
296 const char *mbName
= nameBuf
;
298 const char *mbName
= name
.c_str();
303 bool notGoingToFit
= false;
304 size_t len
= strlen(mbName
);
305 size_t maxname
= Len(TAR_NAME
);
306 size_t maxprefix
= Len(TAR_PREFIX
);
311 fits
= i
< maxprefix
&& len
- i
<= maxname
;
314 const char *p
= strchr(mbName
+ i
, '/');
316 nexti
= p
- mbName
+ 1;
317 if (!p
|| nexti
- 1 > maxprefix
)
318 notGoingToFit
= true;
321 if (fits
|| notGoingToFit
) {
322 strncpy(Get(TAR_NAME
), mbName
+ i
, maxname
);
324 strncpy(Get(TAR_PREFIX
), mbName
, i
- 1);
331 return fits
&& !badconv
;
335 /////////////////////////////////////////////////////////////////////////////
338 static wxFileOffset
RoundUpSize(wxFileOffset size
, int factor
= 1)
340 wxFileOffset chunk
= TAR_BLOCKSIZE
* factor
;
341 return ((size
+ chunk
- 1) / chunk
) * chunk
;
344 static wxString
GroupName()
348 if ((gr
= getgrgid(getgid())) != NULL
)
349 return wxString(gr
->gr_name
, wxConvLibc
);
354 static inline int UserId()
363 static inline int GroupId()
372 // ignore the size field for entry types 3, 4, 5 and 6
374 static inline wxFileOffset
GetDataSize(const wxTarEntry
& entry
)
376 switch (entry
.GetTypeFlag()) {
383 return entry
.GetSize();
388 /////////////////////////////////////////////////////////////////////////////
390 // Holds all the meta-data for a file in the tar
392 wxTarEntry::wxTarEntry(const wxString
& name
/*=wxEmptyString*/,
393 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
394 wxFileOffset size
/*=0*/)
398 m_GroupId(GroupId()),
400 m_Offset(wxInvalidOffset
),
402 m_TypeFlag(wxTAR_REGTYPE
),
403 m_UserName(wxGetUserId()),
404 m_GroupName(GroupName()),
412 wxTarEntry::~wxTarEntry()
416 wxTarEntry::wxTarEntry(const wxTarEntry
& e
)
420 m_IsModeSet(e
.m_IsModeSet
),
421 m_UserId(e
.m_UserId
),
422 m_GroupId(e
.m_GroupId
),
424 m_Offset(e
.m_Offset
),
425 m_ModifyTime(e
.m_ModifyTime
),
426 m_AccessTime(e
.m_AccessTime
),
427 m_CreateTime(e
.m_CreateTime
),
428 m_TypeFlag(e
.m_TypeFlag
),
429 m_LinkName(e
.m_LinkName
),
430 m_UserName(e
.m_UserName
),
431 m_GroupName(e
.m_GroupName
),
432 m_DevMajor(e
.m_DevMajor
),
433 m_DevMinor(e
.m_DevMinor
)
437 wxTarEntry
& wxTarEntry::operator=(const wxTarEntry
& e
)
442 m_IsModeSet
= e
.m_IsModeSet
;
443 m_UserId
= e
.m_UserId
;
444 m_GroupId
= e
.m_GroupId
;
446 m_Offset
= e
.m_Offset
;
447 m_ModifyTime
= e
.m_ModifyTime
;
448 m_AccessTime
= e
.m_AccessTime
;
449 m_CreateTime
= e
.m_CreateTime
;
450 m_TypeFlag
= e
.m_TypeFlag
;
451 m_LinkName
= e
.m_LinkName
;
452 m_UserName
= e
.m_UserName
;
453 m_GroupName
= e
.m_GroupName
;
454 m_DevMajor
= e
.m_DevMajor
;
455 m_DevMinor
= e
.m_DevMinor
;
460 wxString
wxTarEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
462 bool isDir
= IsDir() && !m_Name
.empty();
464 // optimisations for common (and easy) cases
465 switch (wxFileName::GetFormat(format
)) {
468 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
469 for (size_t i
= 0; i
< name
.length(); i
++)
470 if (name
[i
] == _T('/'))
476 return isDir
? m_Name
+ _T("/") : m_Name
;
485 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
487 fn
.Assign(m_Name
, wxPATH_UNIX
);
489 return fn
.GetFullPath(format
);
492 void wxTarEntry::SetName(const wxString
& name
, wxPathFormat format
)
495 m_Name
= GetInternalName(name
, format
, &isDir
);
499 // Static - Internally tars and zips use forward slashes for the path
500 // separator, absolute paths aren't allowed, and directory names have a
501 // trailing slash. This function converts a path into this internal format,
502 // but without a trailing slash for a directory.
504 wxString
wxTarEntry::GetInternalName(const wxString
& name
,
505 wxPathFormat format
/*=wxPATH_NATIVE*/,
506 bool *pIsDir
/*=NULL*/)
510 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
511 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
515 bool isDir
= !internal
.empty() && internal
.Last() == '/';
519 internal
.erase(internal
.length() - 1);
521 while (!internal
.empty() && *internal
.begin() == '/')
522 internal
.erase(0, 1);
523 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
524 internal
.erase(0, 2);
525 if (internal
== _T(".") || internal
== _T(".."))
526 internal
= wxEmptyString
;
531 bool wxTarEntry::IsDir() const
533 return m_TypeFlag
== wxTAR_DIRTYPE
;
536 void wxTarEntry::SetIsDir(bool isDir
)
539 m_TypeFlag
= wxTAR_DIRTYPE
;
540 else if (m_TypeFlag
== wxTAR_DIRTYPE
)
541 m_TypeFlag
= wxTAR_REGTYPE
;
544 void wxTarEntry::SetIsReadOnly(bool isReadOnly
)
552 int wxTarEntry::GetMode() const
554 if (m_IsModeSet
|| !IsDir())
557 return m_Mode
| 0111;
561 void wxTarEntry::SetMode(int mode
)
563 m_Mode
= mode
& 07777;
568 /////////////////////////////////////////////////////////////////////////////
571 wxDECLARE_SCOPED_PTR(wxTarEntry
, wxTarEntryPtr_
)
572 wxDEFINE_SCOPED_PTR (wxTarEntry
, wxTarEntryPtr_
)
574 wxTarInputStream::wxTarInputStream(wxInputStream
& stream
,
575 wxMBConv
& conv
/*=wxConvLocal*/)
576 : wxArchiveInputStream(stream
, conv
)
581 wxTarInputStream::wxTarInputStream(wxInputStream
*stream
,
582 wxMBConv
& conv
/*=wxConvLocal*/)
583 : wxArchiveInputStream(stream
, conv
)
588 void wxTarInputStream::Init()
590 m_pos
= wxInvalidOffset
;
592 m_size
= wxInvalidOffset
;
593 m_sumType
= SUM_UNKNOWN
;
594 m_tarType
= TYPE_USTAR
;
595 m_hdr
= new wxTarHeaderBlock
;
597 m_GlobalHeaderRecs
= NULL
;
598 m_lasterror
= m_parent_i_stream
->GetLastError();
601 wxTarInputStream::~wxTarInputStream()
605 delete m_GlobalHeaderRecs
;
608 wxTarEntry
*wxTarInputStream::GetNextEntry()
610 m_lasterror
= ReadHeaders();
615 wxTarEntryPtr_
entry(new wxTarEntry
);
617 entry
->SetMode(GetHeaderNumber(TAR_MODE
));
618 entry
->SetUserId(GetHeaderNumber(TAR_UID
));
619 entry
->SetGroupId(GetHeaderNumber(TAR_UID
));
620 entry
->SetSize(GetHeaderNumber(TAR_SIZE
));
622 entry
->SetOffset(m_offset
);
624 entry
->SetDateTime(GetHeaderDate(_T("mtime")));
625 entry
->SetAccessTime(GetHeaderDate(_T("atime")));
626 entry
->SetCreateTime(GetHeaderDate(_T("ctime")));
628 entry
->SetTypeFlag(*m_hdr
->Get(TAR_TYPEFLAG
));
629 bool isDir
= entry
->IsDir();
631 entry
->SetLinkName(GetHeaderString(TAR_LINKNAME
));
633 if (m_tarType
!= TYPE_OLDTAR
) {
634 entry
->SetUserName(GetHeaderString(TAR_UNAME
));
635 entry
->SetGroupName(GetHeaderString(TAR_GNAME
));
637 entry
->SetDevMajor(GetHeaderNumber(TAR_DEVMAJOR
));
638 entry
->SetDevMinor(GetHeaderNumber(TAR_DEVMINOR
));
641 entry
->SetName(GetHeaderPath(), wxPATH_UNIX
);
646 m_HeaderRecs
->clear();
648 m_size
= GetDataSize(*entry
);
651 return entry
.release();
654 bool wxTarInputStream::OpenEntry(wxTarEntry
& entry
)
656 wxFileOffset offset
= entry
.GetOffset();
658 if (GetLastError() != wxSTREAM_READ_ERROR
659 && m_parent_i_stream
->IsSeekable()
660 && m_parent_i_stream
->SeekI(offset
) == offset
)
663 m_size
= GetDataSize(entry
);
665 m_lasterror
= wxSTREAM_NO_ERROR
;
668 m_lasterror
= wxSTREAM_READ_ERROR
;
673 bool wxTarInputStream::OpenEntry(wxArchiveEntry
& entry
)
675 wxTarEntry
*tarEntry
= wxStaticCast(&entry
, wxTarEntry
);
676 return tarEntry
? OpenEntry(*tarEntry
) : false;
679 bool wxTarInputStream::CloseEntry()
681 if (m_lasterror
== wxSTREAM_READ_ERROR
)
686 wxFileOffset size
= RoundUpSize(m_size
);
687 wxFileOffset remainder
= size
- m_pos
;
689 if (remainder
&& m_parent_i_stream
->IsSeekable()) {
691 if (m_parent_i_stream
->SeekI(remainder
, wxFromCurrent
)
697 const int BUFSIZE
= 8192;
698 wxCharBuffer
buf(BUFSIZE
);
700 while (remainder
> 0 && m_parent_i_stream
->IsOk())
701 remainder
-= m_parent_i_stream
->Read(
702 buf
.data(), wxMin(BUFSIZE
, remainder
)).LastRead();
705 m_pos
= wxInvalidOffset
;
707 m_lasterror
= m_parent_i_stream
->GetLastError();
712 wxStreamError
wxTarInputStream::ReadHeaders()
715 return wxSTREAM_READ_ERROR
;
720 m_hdr
->Read(*m_parent_i_stream
);
721 if (m_parent_i_stream
->Eof())
722 wxLogError(_("incomplete header block in tar"));
723 if (!*m_parent_i_stream
)
724 return wxSTREAM_READ_ERROR
;
725 m_offset
+= TAR_BLOCKSIZE
;
727 // an all-zero header marks the end of the tar
728 if (m_hdr
->IsAllZeros())
731 // the checksum is supposed to be the unsigned sum of the header bytes,
732 // but there have been versions of tar that used the signed sum, so
733 // accept that too, but only if used throughout.
734 wxUint32 chksum
= m_hdr
->GetOctal(TAR_CHKSUM
);
737 if (m_sumType
!= SUM_SIGNED
) {
738 ok
= chksum
== m_hdr
->Sum();
739 if (m_sumType
== SUM_UNKNOWN
)
740 m_sumType
= ok
? SUM_UNSIGNED
: SUM_SIGNED
;
742 if (m_sumType
== SUM_SIGNED
)
743 ok
= chksum
== m_hdr
->Sum(true);
745 wxLogError(_("checksum failure reading tar header block"));
746 return wxSTREAM_READ_ERROR
;
749 if (strcmp(m_hdr
->Get(TAR_MAGIC
), USTAR_MAGIC
) == 0)
750 m_tarType
= TYPE_USTAR
;
751 else if (strcmp(m_hdr
->Get(TAR_MAGIC
), GNU_MAGIC
) == 0 &&
752 strcmp(m_hdr
->Get(TAR_VERSION
), GNU_VERION
) == 0)
753 m_tarType
= TYPE_GNUTAR
;
755 m_tarType
= TYPE_OLDTAR
;
757 if (m_tarType
!= TYPE_USTAR
)
760 switch (*m_hdr
->Get(TAR_TYPEFLAG
)) {
761 case 'g': ReadExtendedHeader(m_GlobalHeaderRecs
); break;
762 case 'x': ReadExtendedHeader(m_HeaderRecs
); break;
763 default: done
= true;
767 return wxSTREAM_NO_ERROR
;
770 wxString
wxTarInputStream::GetExtendedHeader(const wxString
& key
) const
772 wxTarHeaderRecords::iterator it
;
774 // look at normal extended header records first
776 it
= m_HeaderRecs
->find(key
);
777 if (it
!= m_HeaderRecs
->end())
778 return wxString(it
->second
.wc_str(wxConvUTF8
), GetConv());
781 // if not found, look at the global header records
782 if (m_GlobalHeaderRecs
) {
783 it
= m_GlobalHeaderRecs
->find(key
);
784 if (it
!= m_GlobalHeaderRecs
->end())
785 return wxString(it
->second
.wc_str(wxConvUTF8
), GetConv());
788 return wxEmptyString
;
791 wxString
wxTarInputStream::GetHeaderPath() const
795 if ((path
= GetExtendedHeader(_T("path"))) != wxEmptyString
)
798 path
= wxString(m_hdr
->Get(TAR_NAME
), GetConv());
799 if (m_tarType
!= TYPE_USTAR
)
802 const char *prefix
= m_hdr
->Get(TAR_PREFIX
);
803 return *prefix
? wxString(prefix
, GetConv()) + _T("/") + path
: path
;
806 wxDateTime
wxTarInputStream::GetHeaderDate(const wxString
& key
) const
810 // try extended header, stored as decimal seconds since the epoch
811 if ((value
= GetExtendedHeader(key
)) != wxEmptyString
) {
813 ll
.Assign(wxAtof(value
) * 1000.0);
817 if (key
== _T("mtime"))
818 return wxLongLong(m_hdr
->GetOctal(TAR_MTIME
)) * 1000L;
823 wxTarNumber
wxTarInputStream::GetHeaderNumber(int id
) const
827 if ((value
= GetExtendedHeader(m_hdr
->Name(id
))) != wxEmptyString
) {
829 const wxChar
*p
= value
;
833 n
= n
* 10 + (*p
++ - '0');
836 return m_hdr
->GetOctal(id
);
840 wxString
wxTarInputStream::GetHeaderString(int id
) const
844 if ((value
= GetExtendedHeader(m_hdr
->Name(id
))) != wxEmptyString
)
847 return wxString(m_hdr
->Get(id
), GetConv());
850 // An extended header consists of one or more records, each constructed:
851 // "%d %s=%s\n", <length>, <keyword>, <value>
852 // <length> is the byte length, <keyword> and <value> are UTF-8
854 bool wxTarInputStream::ReadExtendedHeader(wxTarHeaderRecords
*& recs
)
857 recs
= new wxTarHeaderRecords
;
859 // round length up to a whole number of blocks
860 size_t len
= m_hdr
->GetOctal(TAR_SIZE
);
861 size_t size
= RoundUpSize(len
);
863 // read in the whole header since it should be small
864 wxCharBuffer
buf(size
);
865 size_t lastread
= m_parent_i_stream
->Read(buf
.data(), size
).LastRead();
869 m_offset
+= lastread
;
871 size_t recPos
, recSize
;
874 for (recPos
= 0; recPos
< len
; recPos
+= recSize
) {
875 char *pRec
= buf
.data() + recPos
;
878 // read the record size (byte count in ascii decimal)
881 recSize
= recSize
* 10 + *p
++ - '0';
884 if (recPos
+ recSize
> len
)
886 if (recSize
< p
- pRec
+ (size_t)3 || *p
!= ' '
887 || pRec
[recSize
- 1] != '\012') {
892 // replace the final '\n' with a nul, to terminate value
893 pRec
[recSize
- 1] = 0;
894 // the key is here, following the space
897 // look forward for the '=', the value follows
898 while (*p
&& *p
!= '=')
904 // replace the '=' with a nul, to terminate the key
907 wxString
key(wxConvUTF8
.cMB2WC(pKey
), GetConv());
908 wxString
value(wxConvUTF8
.cMB2WC(p
), GetConv());
910 // an empty value unsets a previously given value
914 (*recs
)[key
] = value
;
917 if (!ok
|| recPos
< len
|| size
!= lastread
) {
918 wxLogWarning(_("invalid data in extended tar header"));
925 wxFileOffset
wxTarInputStream::OnSysSeek(wxFileOffset pos
, wxSeekMode mode
)
928 wxLogError(_("tar entry not open"));
929 m_lasterror
= wxSTREAM_READ_ERROR
;
932 return wxInvalidOffset
;
935 case wxFromStart
: break;
936 case wxFromCurrent
: pos
+= m_pos
; break;
937 case wxFromEnd
: pos
+= m_size
; break;
940 if (pos
< 0 || m_parent_i_stream
->SeekI(m_offset
+ pos
) == wxInvalidOffset
)
941 return wxInvalidOffset
;
947 size_t wxTarInputStream::OnSysRead(void *buffer
, size_t size
)
950 wxLogError(_("tar entry not open"));
951 m_lasterror
= wxSTREAM_READ_ERROR
;
953 if (!IsOk() || !size
)
958 else if (m_pos
+ size
> m_size
+ (size_t)0)
959 size
= m_size
- m_pos
;
961 size_t lastread
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
964 if (m_pos
>= m_size
) {
965 m_lasterror
= wxSTREAM_EOF
;
966 } else if (!m_parent_i_stream
->IsOk()) {
967 // any other error will have been reported by the underlying stream
968 if (m_parent_i_stream
->Eof())
969 wxLogError(_("unexpected end of file"));
970 m_lasterror
= wxSTREAM_READ_ERROR
;
977 /////////////////////////////////////////////////////////////////////////////
980 wxTarOutputStream::wxTarOutputStream(wxOutputStream
& stream
,
981 wxTarFormat format
/*=wxTAR_PAX*/,
982 wxMBConv
& conv
/*=wxConvLocal*/)
983 : wxArchiveOutputStream(stream
, conv
)
988 wxTarOutputStream::wxTarOutputStream(wxOutputStream
*stream
,
989 wxTarFormat format
/*=wxTAR_PAX*/,
990 wxMBConv
& conv
/*=wxConvLocal*/)
991 : wxArchiveOutputStream(stream
, conv
)
996 void wxTarOutputStream::Init(wxTarFormat format
)
998 m_pos
= wxInvalidOffset
;
999 m_maxpos
= wxInvalidOffset
;
1000 m_size
= wxInvalidOffset
;
1001 m_headpos
= wxInvalidOffset
;
1002 m_datapos
= wxInvalidOffset
;
1003 m_tarstart
= wxInvalidOffset
;
1005 m_pax
= format
== wxTAR_PAX
;
1006 m_BlockingFactor
= m_pax
? 10 : 20;
1009 m_hdr
= new wxTarHeaderBlock
;
1011 m_extendedHdr
= NULL
;
1013 m_lasterror
= m_parent_o_stream
->GetLastError();
1016 wxTarOutputStream::~wxTarOutputStream()
1022 delete [] m_extendedHdr
;
1025 bool wxTarOutputStream::PutNextEntry(wxTarEntry
*entry
)
1027 wxTarEntryPtr_
e(entry
);
1034 m_tarstart
= m_parent_o_stream
->TellO();
1037 if (m_tarstart
!= wxInvalidOffset
)
1038 m_headpos
= m_tarstart
+ m_tarsize
;
1040 if (WriteHeaders(*e
)) {
1043 m_size
= GetDataSize(*e
);
1044 if (m_tarstart
!= wxInvalidOffset
)
1045 m_datapos
= m_tarstart
+ m_tarsize
;
1047 // types that are not allowd any data
1048 const char nodata
[] = {
1049 wxTAR_LNKTYPE
, wxTAR_SYMTYPE
, wxTAR_CHRTYPE
, wxTAR_BLKTYPE
,
1050 wxTAR_DIRTYPE
, wxTAR_FIFOTYPE
, 0
1052 int typeflag
= e
->GetTypeFlag();
1054 // pax does now allow data for wxTAR_LNKTYPE
1055 if (!m_pax
|| typeflag
!= wxTAR_LNKTYPE
)
1056 if (strchr(nodata
, typeflag
) != NULL
)
1063 bool wxTarOutputStream::PutNextEntry(const wxString
& name
,
1064 const wxDateTime
& dt
,
1067 return PutNextEntry(new wxTarEntry(name
, dt
, size
));
1070 bool wxTarOutputStream::PutNextDirEntry(const wxString
& name
,
1071 const wxDateTime
& dt
)
1073 wxTarEntry
*entry
= new wxTarEntry(name
, dt
);
1075 return PutNextEntry(entry
);
1078 bool wxTarOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1080 wxTarEntry
*tarEntry
= wxStaticCast(entry
, wxTarEntry
);
1083 return PutNextEntry(tarEntry
);
1086 bool wxTarOutputStream::CopyEntry(wxTarEntry
*entry
,
1087 wxTarInputStream
& inputStream
)
1089 if (PutNextEntry(entry
))
1091 return IsOk() && inputStream
.Eof();
1094 bool wxTarOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1095 wxArchiveInputStream
& inputStream
)
1097 if (PutNextEntry(entry
))
1099 return IsOk() && inputStream
.Eof();
1102 bool wxTarOutputStream::CloseEntry()
1107 if (m_pos
< m_maxpos
) {
1108 wxASSERT(m_parent_o_stream
->IsSeekable());
1109 m_parent_o_stream
->SeekO(m_datapos
+ m_maxpos
);
1110 m_lasterror
= m_parent_o_stream
->GetLastError();
1115 wxFileOffset size
= RoundUpSize(m_pos
);
1117 memset(m_hdr
, 0, size
- m_pos
);
1118 m_parent_o_stream
->Write(m_hdr
, size
- m_pos
);
1119 m_lasterror
= m_parent_o_stream
->GetLastError();
1124 if (IsOk() && m_pos
!= m_size
)
1127 m_pos
= wxInvalidOffset
;
1128 m_maxpos
= wxInvalidOffset
;
1129 m_size
= wxInvalidOffset
;
1130 m_headpos
= wxInvalidOffset
;
1131 m_datapos
= wxInvalidOffset
;
1136 bool wxTarOutputStream::Close()
1141 memset(m_hdr
, 0, sizeof(*m_hdr
));
1142 int count
= (RoundUpSize(m_tarsize
+ 2 * TAR_BLOCKSIZE
, m_BlockingFactor
)
1143 - m_tarsize
) / TAR_BLOCKSIZE
;
1145 m_parent_o_stream
->Write(m_hdr
, TAR_BLOCKSIZE
);
1148 m_tarstart
= wxInvalidOffset
;
1149 m_lasterror
= m_parent_o_stream
->GetLastError();
1153 bool wxTarOutputStream::WriteHeaders(wxTarEntry
& entry
)
1155 memset(m_hdr
, 0, sizeof(*m_hdr
));
1157 SetHeaderPath(entry
.GetName(wxPATH_UNIX
));
1159 SetHeaderNumber(TAR_MODE
, entry
.GetMode());
1160 SetHeaderNumber(TAR_UID
, entry
.GetUserId());
1161 SetHeaderNumber(TAR_GID
, entry
.GetGroupId());
1163 if (entry
.GetSize() == wxInvalidOffset
)
1165 m_large
= !SetHeaderNumber(TAR_SIZE
, entry
.GetSize());
1167 SetHeaderDate(_T("mtime"), entry
.GetDateTime());
1168 if (entry
.GetAccessTime().IsValid())
1169 SetHeaderDate(_T("atime"), entry
.GetAccessTime());
1170 if (entry
.GetCreateTime().IsValid())
1171 SetHeaderDate(_T("ctime"), entry
.GetCreateTime());
1173 *m_hdr
->Get(TAR_TYPEFLAG
) = char(entry
.GetTypeFlag());
1175 strcpy(m_hdr
->Get(TAR_MAGIC
), USTAR_MAGIC
);
1176 strcpy(m_hdr
->Get(TAR_VERSION
), USTAR_VERSION
);
1178 SetHeaderString(TAR_LINKNAME
, entry
.GetLinkName());
1179 SetHeaderString(TAR_UNAME
, entry
.GetUserName());
1180 SetHeaderString(TAR_GNAME
, entry
.GetGroupName());
1182 if (~entry
.GetDevMajor())
1183 SetHeaderNumber(TAR_DEVMAJOR
, entry
.GetDevMajor());
1184 if (~entry
.GetDevMinor())
1185 SetHeaderNumber(TAR_DEVMINOR
, entry
.GetDevMinor());
1187 m_chksum
= m_hdr
->Sum();
1188 m_hdr
->SetOctal(TAR_CHKSUM
, m_chksum
);
1190 m_chksum
-= m_hdr
->SumField(TAR_SIZE
);
1192 // The main header is now fully prepared so we know what extended headers
1193 // (if any) will be needed. Output any extended headers before writing
1195 if (m_extendedHdr
&& *m_extendedHdr
) {
1197 // the extended headers are written to the tar as a file entry,
1198 // so prepare a regular header block for the pseudo-file.
1200 m_hdr2
= new wxTarHeaderBlock
;
1201 memset(m_hdr2
, 0, sizeof(*m_hdr2
));
1203 // an old tar that doesn't understand extended headers will
1204 // extract it as a file, so give these fields reasonable values
1205 // so that the user will have access to read and remove it.
1206 m_hdr2
->SetPath(PaxHeaderPath(_T("%d/PaxHeaders.%p/%f"),
1207 entry
.GetName(wxPATH_UNIX
)), GetConv());
1208 m_hdr2
->SetOctal(TAR_MODE
, 0600);
1209 strcpy(m_hdr2
->Get(TAR_UID
), m_hdr
->Get(TAR_UID
));
1210 strcpy(m_hdr2
->Get(TAR_GID
), m_hdr
->Get(TAR_GID
));
1211 size_t length
= strlen(m_extendedHdr
);
1212 m_hdr2
->SetOctal(TAR_SIZE
, length
);
1213 strcpy(m_hdr2
->Get(TAR_MTIME
), m_hdr
->Get(TAR_MTIME
));
1214 *m_hdr2
->Get(TAR_TYPEFLAG
) = 'x';
1215 strcpy(m_hdr2
->Get(TAR_MAGIC
), USTAR_MAGIC
);
1216 strcpy(m_hdr2
->Get(TAR_VERSION
), USTAR_VERSION
);
1217 strcpy(m_hdr2
->Get(TAR_UNAME
), m_hdr
->Get(TAR_UNAME
));
1218 strcpy(m_hdr2
->Get(TAR_GNAME
), m_hdr
->Get(TAR_GNAME
));
1220 m_hdr2
->SetOctal(TAR_CHKSUM
, m_hdr2
->Sum());
1222 m_hdr2
->Write(*m_parent_o_stream
);
1223 m_tarsize
+= TAR_BLOCKSIZE
;
1225 size_t rounded
= RoundUpSize(length
);
1226 memset(m_extendedHdr
+ length
, 0, rounded
- length
);
1227 m_parent_o_stream
->Write(m_extendedHdr
, rounded
);
1228 m_tarsize
+= rounded
;
1233 // if don't have extended headers just report error
1234 if (!m_badfit
.empty()) {
1236 wxLogWarning(_("%s did not fit the tar header for entry '%s'"),
1237 m_badfit
.c_str(), entry
.GetName().c_str());
1241 m_hdr
->Write(*m_parent_o_stream
);
1242 m_tarsize
+= TAR_BLOCKSIZE
;
1243 m_lasterror
= m_parent_o_stream
->GetLastError();
1248 wxString
wxTarOutputStream::PaxHeaderPath(const wxString
& format
,
1249 const wxString
& path
)
1251 wxString d
= path
.BeforeLast(_T('/'));
1252 wxString f
= path
.AfterLast(_T('/'));
1258 ret
.reserve(format
.length() + path
.length() + 16);
1264 end
= format
.find('%', begin
);
1265 if (end
== wxString::npos
|| end
+ 1 >= format
.length())
1267 ret
<< format
.substr(begin
, end
- begin
);
1268 switch (format
[end
+ 1]) {
1269 case 'd': ret
<< d
; break;
1270 case 'f': ret
<< f
; break;
1271 case 'p': ret
<< wxGetProcessId(); break;
1272 case '%': ret
<< _T("%"); break;
1277 ret
<< format
.substr(begin
);
1282 bool wxTarOutputStream::ModifyHeader()
1284 wxFileOffset originalPos
= wxInvalidOffset
;
1285 wxFileOffset sizePos
= wxInvalidOffset
;
1287 if (!m_large
&& m_headpos
!= wxInvalidOffset
1288 && m_parent_o_stream
->IsSeekable())
1291 originalPos
= m_parent_o_stream
->TellO();
1292 if (originalPos
!= wxInvalidOffset
)
1294 m_parent_o_stream
->SeekO(m_headpos
+ m_hdr
->Offset(TAR_SIZE
));
1297 if (sizePos
== wxInvalidOffset
|| !m_hdr
->SetOctal(TAR_SIZE
, m_pos
)) {
1298 wxLogError(_("incorrect size given for tar entry"));
1299 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1303 m_chksum
+= m_hdr
->SumField(TAR_SIZE
);
1304 m_hdr
->SetOctal(TAR_CHKSUM
, m_chksum
);
1305 wxFileOffset sumPos
= m_headpos
+ m_hdr
->Offset(TAR_CHKSUM
);
1308 m_hdr
->WriteField(*m_parent_o_stream
, TAR_SIZE
) &&
1309 m_parent_o_stream
->SeekO(sumPos
) == sumPos
&&
1310 m_hdr
->WriteField(*m_parent_o_stream
, TAR_CHKSUM
) &&
1311 m_parent_o_stream
->SeekO(originalPos
) == originalPos
;
1314 void wxTarOutputStream::SetHeaderPath(const wxString
& name
)
1316 if (!m_hdr
->SetPath(name
, GetConv()) || (m_pax
&& !name
.IsAscii()))
1317 SetExtendedHeader(_T("path"), name
);
1320 bool wxTarOutputStream::SetHeaderNumber(int id
, wxTarNumber n
)
1322 if (m_hdr
->SetOctal(id
, n
)) {
1325 SetExtendedHeader(m_hdr
->Name(id
), wxLongLong(n
).ToString());
1330 void wxTarOutputStream::SetHeaderString(int id
, const wxString
& str
)
1332 strncpy(m_hdr
->Get(id
), str
.mb_str(GetConv()), m_hdr
->Len(id
));
1333 if (str
.length() > m_hdr
->Len(id
))
1334 SetExtendedHeader(m_hdr
->Name(id
), str
);
1337 void wxTarOutputStream::SetHeaderDate(const wxString
& key
,
1338 const wxDateTime
& datetime
)
1340 wxLongLong ll
= datetime
.IsValid() ? datetime
.GetValue() : wxLongLong(0);
1341 wxLongLong secs
= ll
/ 1000L;
1343 if (key
!= _T("mtime")
1344 || !m_hdr
->SetOctal(TAR_MTIME
, wxTarNumber(secs
.GetValue()))
1345 || secs
<= 0 || secs
>= 0x7fffffff)
1348 if (ll
>= LONG_MIN
&& ll
<= LONG_MAX
) {
1349 str
.Printf(_T("%g"), ll
.ToLong() / 1000.0);
1351 str
= ll
.ToString();
1352 str
.insert(str
.end() - 3, '.');
1354 SetExtendedHeader(key
, str
);
1358 void wxTarOutputStream::SetExtendedHeader(const wxString
& key
,
1359 const wxString
& value
)
1362 const wxWX2WCbuf wide_key
= key
.wc_str(GetConv());
1363 const wxCharBuffer utf_key
= wxConvUTF8
.cWC2MB(wide_key
);
1365 const wxWX2WCbuf wide_value
= value
.wc_str(GetConv());
1366 const wxCharBuffer utf_value
= wxConvUTF8
.cWC2MB(wide_value
);
1368 // a small buffer to format the length field in
1370 // length of "99<space><key>=<value>\n"
1371 unsigned long length
= strlen(utf_value
) + strlen(utf_key
) + 5;
1372 sprintf(buf
, "%lu", length
);
1373 // the length includes itself
1374 size_t lenlen
= strlen(buf
);
1376 length
+= lenlen
- 2;
1377 sprintf(buf
, "%lu", length
);
1378 if (strlen(buf
) > lenlen
)
1379 sprintf(buf
, "%lu", ++length
);
1382 // reallocate m_extendedHdr if it's not big enough
1383 if (m_extendedSize
< length
) {
1384 size_t rounded
= RoundUpSize(length
);
1385 m_extendedSize
<<= 1;
1386 if (rounded
> m_extendedSize
)
1387 m_extendedSize
= rounded
;
1388 char *oldHdr
= m_extendedHdr
;
1389 m_extendedHdr
= new char[m_extendedSize
];
1391 strcpy(m_extendedHdr
, oldHdr
);
1398 // append the new record
1399 char *append
= strchr(m_extendedHdr
, 0);
1400 sprintf(append
, "%s %s=%s\012", buf
,
1401 (const char*)utf_key
, (const char*)utf_value
);
1404 // if not pax then make a list of fields to report as errors
1405 if (!m_badfit
.empty())
1406 m_badfit
+= _T(", ");
1411 void wxTarOutputStream::Sync()
1413 m_parent_o_stream
->Sync();
1416 wxFileOffset
wxTarOutputStream::OnSysSeek(wxFileOffset pos
, wxSeekMode mode
)
1419 wxLogError(_("tar entry not open"));
1420 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1422 if (!IsOk() || m_datapos
== wxInvalidOffset
)
1423 return wxInvalidOffset
;
1426 case wxFromStart
: break;
1427 case wxFromCurrent
: pos
+= m_pos
; break;
1428 case wxFromEnd
: pos
+= m_maxpos
; break;
1431 if (pos
< 0 || m_parent_o_stream
->SeekO(m_datapos
+ pos
) == wxInvalidOffset
)
1432 return wxInvalidOffset
;
1438 size_t wxTarOutputStream::OnSysWrite(const void *buffer
, size_t size
)
1441 wxLogError(_("tar entry not open"));
1442 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1444 if (!IsOk() || !size
)
1447 size_t lastwrite
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
1449 if (m_pos
> m_maxpos
)
1452 if (lastwrite
!= size
)
1453 m_lasterror
= wxSTREAM_WRITE_ERROR
;
1458 #endif // wxUSE_TARSTREAM