FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[Original HTTPS Page]
cpython/Lib/tarfile.py at 3.5 · python/cpython · GitHub
python
cpython
Repository navigation
Code
Issues
5k+
(5k+)
Pull requests
2.7k
(2.7k)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Lib
/
tarfile.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
executable file
·
2552 lines (2230 loc) · 91 KB
Breadcrumbs
cpython
/
Lib
/
tarfile.py
Copy path
File metadata and controls
executable file
·
2552 lines (2230 loc) · 91 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#-------------------------------------------------------------------
# tarfile.py
#-------------------------------------------------------------------
# Copyright (C) 2002 Lars Gustaebel <lars@gustaebel.de>
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
"""Read from and write to tar format archives.
"""
version
=
"0.9.0"
__author__
=
"Lars Gust
\u00e4
bel (lars@gustaebel.de)"
__date__
=
"$Date: 2011-02-25 17:42:01 +0200 (Fri, 25 Feb 2011) $"
__cvsid__
=
"$Id: tarfile.py 88586 2011-02-25 15:42:01Z marc-andre.lemburg $"
__credits__
=
"Gustavo Niemeyer, Niels Gust
\u00e4
bel, Richard Townsend."
#---------
# Imports
#---------
from
builtins
import
open
as
bltn_open
import
sys
import
os
import
io
import
shutil
import
stat
import
time
import
struct
import
copy
import
re
try
:
import
grp
,
pwd
except
ImportError
:
grp
=
pwd
=
None
# os.symlink on Windows prior to 6.0 raises NotImplementedError
symlink_exception
=
(
AttributeError
,
NotImplementedError
)
try
:
# OSError (winerror=1314) will be raised if the caller does not hold the
# SeCreateSymbolicLinkPrivilege privilege
symlink_exception
+=
(
OSError
,)
except
NameError
:
pass
# from tarfile import *
__all__
=
[
"TarFile"
,
"TarInfo"
,
"is_tarfile"
,
"TarError"
]
#---------------------------------------------------------
# tar constants
#---------------------------------------------------------
NUL
=
b"
\0
"
# the null character
BLOCKSIZE
=
512
# length of processing blocks
RECORDSIZE
=
BLOCKSIZE
*
20
# length of records
GNU_MAGIC
=
b"ustar
\0
"
# magic gnu tar string
POSIX_MAGIC
=
b"ustar
\x00
00"
# magic posix tar string
LENGTH_NAME
=
100
# maximum length of a filename
LENGTH_LINK
=
100
# maximum length of a linkname
LENGTH_PREFIX
=
155
# maximum length of the prefix field
REGTYPE
=
b"0"
# regular file
AREGTYPE
=
b"
\0
"
# regular file
LNKTYPE
=
b"1"
# link (inside tarfile)
SYMTYPE
=
b"2"
# symbolic link
CHRTYPE
=
b"3"
# character special device
BLKTYPE
=
b"4"
# block special device
DIRTYPE
=
b"5"
# directory
FIFOTYPE
=
b"6"
# fifo special device
CONTTYPE
=
b"7"
# contiguous file
GNUTYPE_LONGNAME
=
b"L"
# GNU tar longname
GNUTYPE_LONGLINK
=
b"K"
# GNU tar longlink
GNUTYPE_SPARSE
=
b"S"
# GNU tar sparse file
XHDTYPE
=
b"x"
# POSIX.1-2001 extended header
XGLTYPE
=
b"g"
# POSIX.1-2001 global header
SOLARIS_XHDTYPE
=
b"X"
# Solaris extended header
USTAR_FORMAT
=
0
# POSIX.1-1988 (ustar) format
GNU_FORMAT
=
1
# GNU tar format
PAX_FORMAT
=
2
# POSIX.1-2001 (pax) format
DEFAULT_FORMAT
=
GNU_FORMAT
#---------------------------------------------------------
# tarfile constants
#---------------------------------------------------------
# File types that tarfile supports:
SUPPORTED_TYPES
=
(
REGTYPE
,
AREGTYPE
,
LNKTYPE
,
SYMTYPE
,
DIRTYPE
,
FIFOTYPE
,
CONTTYPE
,
CHRTYPE
,
BLKTYPE
,
GNUTYPE_LONGNAME
,
GNUTYPE_LONGLINK
,
GNUTYPE_SPARSE
)
# File types that will be treated as a regular file.
REGULAR_TYPES
=
(
REGTYPE
,
AREGTYPE
,
CONTTYPE
,
GNUTYPE_SPARSE
)
# File types that are part of the GNU tar format.
GNU_TYPES
=
(
GNUTYPE_LONGNAME
,
GNUTYPE_LONGLINK
,
GNUTYPE_SPARSE
)
# Fields from a pax header that override a TarInfo attribute.
PAX_FIELDS
=
(
"path"
,
"linkpath"
,
"size"
,
"mtime"
,
"uid"
,
"gid"
,
"uname"
,
"gname"
)
# Fields from a pax header that are affected by hdrcharset.
PAX_NAME_FIELDS
=
{
"path"
,
"linkpath"
,
"uname"
,
"gname"
}
# Fields in a pax header that are numbers, all other fields
# are treated as strings.
PAX_NUMBER_FIELDS
=
{
"atime"
:
float
,
"ctime"
:
float
,
"mtime"
:
float
,
"uid"
:
int
,
"gid"
:
int
,
"size"
:
int
}
#---------------------------------------------------------
# initialization
#---------------------------------------------------------
if
os
.
name
in
(
"nt"
,
"ce"
):
ENCODING
=
"utf-8"
else
:
ENCODING
=
sys
.
getfilesystemencoding
()
#---------------------------------------------------------
# Some useful functions
#---------------------------------------------------------
def
stn
(
s
,
length
,
encoding
,
errors
):
"""Convert a string to a null-terminated bytes object.
"""
s
=
s
.
encode
(
encoding
,
errors
)
return
s
[:
length
]
+
(
length
-
len
(
s
))
*
NUL
def
nts
(
s
,
encoding
,
errors
):
"""Convert a null-terminated bytes object to a string.
"""
p
=
s
.
find
(
b"
\0
"
)
if
p
!=
-
1
:
s
=
s
[:
p
]
return
s
.
decode
(
encoding
,
errors
)
def
nti
(
s
):
"""Convert a number field to a python number.
"""
# There are two possible encodings for a number field, see
# itn() below.
if
s
[
0
]
in
(
0o200
,
0o377
):
n
=
0
for
i
in
range
(
len
(
s
)
-
1
):
n
<<=
8
n
+=
s
[
i
+
1
]
if
s
[
0
]
==
0o377
:
n
=
-
(
256
**
(
len
(
s
)
-
1
)
-
n
)
else
:
try
:
s
=
nts
(
s
,
"ascii"
,
"strict"
)
n
=
int
(
s
.
strip
()
or
"0"
,
8
)
except
ValueError
:
raise
InvalidHeaderError
(
"invalid header"
)
return
n
def
itn
(
n
,
digits
=
8
,
format
=
DEFAULT_FORMAT
):
"""Convert a python number to a number field.
"""
# POSIX 1003.1-1988 requires numbers to be encoded as a string of
# octal digits followed by a null-byte, this allows values up to
# (8**(digits-1))-1. GNU tar allows storing numbers greater than
# that if necessary. A leading 0o200 or 0o377 byte indicate this
# particular encoding, the following digits-1 bytes are a big-endian
# base-256 representation. This allows values up to (256**(digits-1))-1.
# A 0o200 byte indicates a positive number, a 0o377 byte a negative
# number.
if
0
<=
n
<
8
**
(
digits
-
1
):
s
=
bytes
(
"%0*o"
%
(
digits
-
1
,
int
(
n
)),
"ascii"
)
+
NUL
elif
format
==
GNU_FORMAT
and
-
256
**
(
digits
-
1
)
<=
n
<
256
**
(
digits
-
1
):
if
n
>=
0
:
s
=
bytearray
([
0o200
])
else
:
s
=
bytearray
([
0o377
])
n
=
256
**
digits
+
n
for
i
in
range
(
digits
-
1
):
s
.
insert
(
1
,
n
&
0o377
)
n
>>=
8
else
:
raise
ValueError
(
"overflow in number field"
)
return
s
def
calc_chksums
(
buf
):
"""Calculate the checksum for a member's header by summing up all
characters except for the chksum field which is treated as if
it was filled with spaces. According to the GNU tar sources,
some tars (Sun and NeXT) calculate chksum with signed char,
which will be different if there are chars in the buffer with
the high bit set. So we calculate two checksums, unsigned and
signed.
"""
unsigned_chksum
=
256
+
sum
(
struct
.
unpack_from
(
"148B8x356B"
,
buf
))
signed_chksum
=
256
+
sum
(
struct
.
unpack_from
(
"148b8x356b"
,
buf
))
return
unsigned_chksum
,
signed_chksum
def
copyfileobj
(
src
,
dst
,
length
=
None
,
exception
=
OSError
):
"""Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content.
"""
if
length
==
0
:
return
if
length
is
None
:
shutil
.
copyfileobj
(
src
,
dst
)
return
BUFSIZE
=
16
*
1024
blocks
,
remainder
=
divmod
(
length
,
BUFSIZE
)
for
b
in
range
(
blocks
):
buf
=
src
.
read
(
BUFSIZE
)
if
len
(
buf
)
<
BUFSIZE
:
raise
exception
(
"unexpected end of data"
)
dst
.
write
(
buf
)
if
remainder
!=
0
:
buf
=
src
.
read
(
remainder
)
if
len
(
buf
)
<
remainder
:
raise
exception
(
"unexpected end of data"
)
dst
.
write
(
buf
)
return
def
filemode
(
mode
):
"""Deprecated in this location; use stat.filemode."""
import
warnings
warnings
.
warn
(
"deprecated in favor of stat.filemode"
,
DeprecationWarning
,
2
)
return
stat
.
filemode
(
mode
)
def
_safe_print
(
s
):
encoding
=
getattr
(
sys
.
stdout
,
'encoding'
,
None
)
if
encoding
is
not
None
:
s
=
s
.
encode
(
encoding
,
'backslashreplace'
).
decode
(
encoding
)
print
(
s
,
end
=
' '
)
class
TarError
(
Exception
):
"""Base exception."""
pass
class
ExtractError
(
TarError
):
"""General exception for extract errors."""
pass
class
ReadError
(
TarError
):
"""Exception for unreadable tar archives."""
pass
class
CompressionError
(
TarError
):
"""Exception for unavailable compression methods."""
pass
class
StreamError
(
TarError
):
"""Exception for unsupported operations on stream-like TarFiles."""
pass
class
HeaderError
(
TarError
):
"""Base exception for header errors."""
pass
class
EmptyHeaderError
(
HeaderError
):
"""Exception for empty headers."""
pass
class
TruncatedHeaderError
(
HeaderError
):
"""Exception for truncated headers."""
pass
class
EOFHeaderError
(
HeaderError
):
"""Exception for end of file headers."""
pass
class
InvalidHeaderError
(
HeaderError
):
"""Exception for invalid headers."""
pass
class
SubsequentHeaderError
(
HeaderError
):
"""Exception for missing and invalid extended headers."""
pass
#---------------------------
# internal stream interface
#---------------------------
class
_LowLevelFile
:
"""Low-level file object. Supports reading and writing.
It is used instead of a regular file object for streaming
access.
"""
def
__init__
(
self
,
name
,
mode
):
mode
=
{
"r"
:
os
.
O_RDONLY
,
"w"
:
os
.
O_WRONLY
|
os
.
O_CREAT
|
os
.
O_TRUNC
,
}[
mode
]
if
hasattr
(
os
,
"O_BINARY"
):
mode
|=
os
.
O_BINARY
self
.
fd
=
os
.
open
(
name
,
mode
,
0o666
)
def
close
(
self
):
os
.
close
(
self
.
fd
)
def
read
(
self
,
size
):
return
os
.
read
(
self
.
fd
,
size
)
def
write
(
self
,
s
):
os
.
write
(
self
.
fd
,
s
)
class
_Stream
:
"""Class that serves as an adapter between TarFile and
a stream-like object. The stream-like object only
needs to have a read() or write() method and is accessed
blockwise. Use of gzip or bzip2 compression is possible.
A stream-like object could be for example: sys.stdin,
sys.stdout, a socket, a tape device etc.
_Stream is intended to be used only internally.
"""
def
__init__
(
self
,
name
,
mode
,
comptype
,
fileobj
,
bufsize
):
"""Construct a _Stream object.
"""
self
.
_extfileobj
=
True
if
fileobj
is
None
:
fileobj
=
_LowLevelFile
(
name
,
mode
)
self
.
_extfileobj
=
False
if
comptype
==
'*'
:
# Enable transparent compression detection for the
# stream interface
fileobj
=
_StreamProxy
(
fileobj
)
comptype
=
fileobj
.
getcomptype
()
self
.
name
=
name
or
""
self
.
mode
=
mode
self
.
comptype
=
comptype
self
.
fileobj
=
fileobj
self
.
bufsize
=
bufsize
self
.
buf
=
b""
self
.
pos
=
0
self
.
closed
=
False
try
:
if
comptype
==
"gz"
:
try
:
import
zlib
except
ImportError
:
raise
CompressionError
(
"zlib module is not available"
)
self
.
zlib
=
zlib
self
.
crc
=
zlib
.
crc32
(
b""
)
if
mode
==
"r"
:
self
.
_init_read_gz
()
self
.
exception
=
zlib
.
error
else
:
self
.
_init_write_gz
()
elif
comptype
==
"bz2"
:
try
:
import
bz2
except
ImportError
:
raise
CompressionError
(
"bz2 module is not available"
)
if
mode
==
"r"
:
self
.
dbuf
=
b""
self
.
cmp
=
bz2
.
BZ2Decompressor
()
self
.
exception
=
OSError
else
:
self
.
cmp
=
bz2
.
BZ2Compressor
()
elif
comptype
==
"xz"
:
try
:
import
lzma
except
ImportError
:
raise
CompressionError
(
"lzma module is not available"
)
if
mode
==
"r"
:
self
.
dbuf
=
b""
self
.
cmp
=
lzma
.
LZMADecompressor
()
self
.
exception
=
lzma
.
LZMAError
else
:
self
.
cmp
=
lzma
.
LZMACompressor
()
elif
comptype
!=
"tar"
:
raise
CompressionError
(
"unknown compression type %r"
%
comptype
)
except
:
if
not
self
.
_extfileobj
:
self
.
fileobj
.
close
()
self
.
closed
=
True
raise
def
__del__
(
self
):
if
hasattr
(
self
,
"closed"
)
and
not
self
.
closed
:
self
.
close
()
def
_init_write_gz
(
self
):
"""Initialize for writing with gzip compression.
"""
self
.
cmp
=
self
.
zlib
.
compressobj
(
9
,
self
.
zlib
.
DEFLATED
,
-
self
.
zlib
.
MAX_WBITS
,
self
.
zlib
.
DEF_MEM_LEVEL
,
0
)
timestamp
=
struct
.
pack
(
"<L"
,
int
(
time
.
time
()))
self
.
__write
(
b"
\037
\213
\010
\010
"
+
timestamp
+
b"
\002
\377
"
)
if
self
.
name
.
endswith
(
".gz"
):
self
.
name
=
self
.
name
[:
-
3
]
# RFC1952 says we must use ISO-8859-1 for the FNAME field.
self
.
__write
(
self
.
name
.
encode
(
"iso-8859-1"
,
"replace"
)
+
NUL
)
def
write
(
self
,
s
):
"""Write string s to the stream.
"""
if
self
.
comptype
==
"gz"
:
self
.
crc
=
self
.
zlib
.
crc32
(
s
,
self
.
crc
)
self
.
pos
+=
len
(
s
)
if
self
.
comptype
!=
"tar"
:
s
=
self
.
cmp
.
compress
(
s
)
self
.
__write
(
s
)
def
__write
(
self
,
s
):
"""Write string s to the stream if a whole new block
is ready to be written.
"""
self
.
buf
+=
s
while
len
(
self
.
buf
)
>
self
.
bufsize
:
self
.
fileobj
.
write
(
self
.
buf
[:
self
.
bufsize
])
self
.
buf
=
self
.
buf
[
self
.
bufsize
:]
def
close
(
self
):
"""Close the _Stream object. No operation should be
done on it afterwards.
"""
if
self
.
closed
:
return
self
.
closed
=
True
try
:
if
self
.
mode
==
"w"
and
self
.
comptype
!=
"tar"
:
self
.
buf
+=
self
.
cmp
.
flush
()
if
self
.
mode
==
"w"
and
self
.
buf
:
self
.
fileobj
.
write
(
self
.
buf
)
self
.
buf
=
b""
if
self
.
comptype
==
"gz"
:
self
.
fileobj
.
write
(
struct
.
pack
(
"<L"
,
self
.
crc
))
self
.
fileobj
.
write
(
struct
.
pack
(
"<L"
,
self
.
pos
&
0xffffFFFF
))
finally
:
if
not
self
.
_extfileobj
:
self
.
fileobj
.
close
()
def
_init_read_gz
(
self
):
"""Initialize for reading a gzip compressed fileobj.
"""
self
.
cmp
=
self
.
zlib
.
decompressobj
(
-
self
.
zlib
.
MAX_WBITS
)
self
.
dbuf
=
b""
# taken from gzip.GzipFile with some alterations
if
self
.
__read
(
2
)
!=
b"
\037
\213
"
:
raise
ReadError
(
"not a gzip file"
)
if
self
.
__read
(
1
)
!=
b"
\010
"
:
raise
CompressionError
(
"unsupported compression method"
)
flag
=
ord
(
self
.
__read
(
1
))
self
.
__read
(
6
)
if
flag
&
4
:
xlen
=
ord
(
self
.
__read
(
1
))
+
256
*
ord
(
self
.
__read
(
1
))
self
.
read
(
xlen
)
if
flag
&
8
:
while
True
:
s
=
self
.
__read
(
1
)
if
not
s
or
s
==
NUL
:
break
if
flag
&
16
:
while
True
:
s
=
self
.
__read
(
1
)
if
not
s
or
s
==
NUL
:
break
if
flag
&
2
:
self
.
__read
(
2
)
def
tell
(
self
):
"""Return the stream's file pointer position.
"""
return
self
.
pos
def
seek
(
self
,
pos
=
0
):
"""Set the stream's file pointer to pos. Negative seeking
is forbidden.
"""
if
pos
-
self
.
pos
>=
0
:
blocks
,
remainder
=
divmod
(
pos
-
self
.
pos
,
self
.
bufsize
)
for
i
in
range
(
blocks
):
self
.
read
(
self
.
bufsize
)
self
.
read
(
remainder
)
else
:
raise
StreamError
(
"seeking backwards is not allowed"
)
return
self
.
pos
def
read
(
self
,
size
=
None
):
"""Return the next size number of bytes from the stream.
If size is not defined, return all bytes of the stream
up to EOF.
"""
if
size
is
None
:
t
=
[]
while
True
:
buf
=
self
.
_read
(
self
.
bufsize
)
if
not
buf
:
break
t
.
append
(
buf
)
buf
=
""
.
join
(
t
)
else
:
buf
=
self
.
_read
(
size
)
self
.
pos
+=
len
(
buf
)
return
buf
def
_read
(
self
,
size
):
"""Return size bytes from the stream.
"""
if
self
.
comptype
==
"tar"
:
return
self
.
__read
(
size
)
c
=
len
(
self
.
dbuf
)
while
c
<
size
:
buf
=
self
.
__read
(
self
.
bufsize
)
if
not
buf
:
break
try
:
buf
=
self
.
cmp
.
decompress
(
buf
)
except
self
.
exception
:
raise
ReadError
(
"invalid compressed data"
)
self
.
dbuf
+=
buf
c
+=
len
(
buf
)
buf
=
self
.
dbuf
[:
size
]
self
.
dbuf
=
self
.
dbuf
[
size
:]
return
buf
def
__read
(
self
,
size
):
"""Return size bytes from stream. If internal buffer is empty,
read another block from the stream.
"""
c
=
len
(
self
.
buf
)
while
c
<
size
:
buf
=
self
.
fileobj
.
read
(
self
.
bufsize
)
if
not
buf
:
break
self
.
buf
+=
buf
c
+=
len
(
buf
)
buf
=
self
.
buf
[:
size
]
self
.
buf
=
self
.
buf
[
size
:]
return
buf
# class _Stream
class
_StreamProxy
(
object
):
"""Small proxy class that enables transparent compression
detection for the Stream interface (mode 'r|*').
"""
def
__init__
(
self
,
fileobj
):
self
.
fileobj
=
fileobj
self
.
buf
=
self
.
fileobj
.
read
(
BLOCKSIZE
)
def
read
(
self
,
size
):
self
.
read
=
self
.
fileobj
.
read
return
self
.
buf
def
getcomptype
(
self
):
if
self
.
buf
.
startswith
(
b"
\x1f
\x8b
\x08
"
):
return
"gz"
elif
self
.
buf
[
0
:
3
]
==
b"BZh"
and
self
.
buf
[
4
:
10
]
==
b"1AY&SY"
:
return
"bz2"
elif
self
.
buf
.
startswith
((
b"
\x5d
\x00
\x00
\x80
"
,
b"
\xfd
7zXZ"
)):
return
"xz"
else
:
return
"tar"
def
close
(
self
):
self
.
fileobj
.
close
()
# class StreamProxy
#------------------------
# Extraction file object
#------------------------
class
_FileInFile
(
object
):
"""A thin wrapper around an existing file object that
provides a part of its data as an individual file
object.
"""
def
__init__
(
self
,
fileobj
,
offset
,
size
,
blockinfo
=
None
):
self
.
fileobj
=
fileobj
self
.
offset
=
offset
self
.
size
=
size
self
.
position
=
0
self
.
name
=
getattr
(
fileobj
,
"name"
,
None
)
self
.
closed
=
False
if
blockinfo
is
None
:
blockinfo
=
[(
0
,
size
)]
# Construct a map with data and zero blocks.
self
.
map_index
=
0
self
.
map
=
[]
lastpos
=
0
realpos
=
self
.
offset
for
offset
,
size
in
blockinfo
:
if
offset
>
lastpos
:
self
.
map
.
append
((
False
,
lastpos
,
offset
,
None
))
self
.
map
.
append
((
True
,
offset
,
offset
+
size
,
realpos
))
realpos
+=
size
lastpos
=
offset
+
size
if
lastpos
<
self
.
size
:
self
.
map
.
append
((
False
,
lastpos
,
self
.
size
,
None
))
def
flush
(
self
):
pass
def
readable
(
self
):
return
True
def
writable
(
self
):
return
False
def
seekable
(
self
):
return
self
.
fileobj
.
seekable
()
def
tell
(
self
):
"""Return the current file position.
"""
return
self
.
position
def
seek
(
self
,
position
,
whence
=
io
.
SEEK_SET
):
"""Seek to a position in the file.
"""
if
whence
==
io
.
SEEK_SET
:
self
.
position
=
min
(
max
(
position
,
0
),
self
.
size
)
elif
whence
==
io
.
SEEK_CUR
:
if
position
<
0
:
self
.
position
=
max
(
self
.
position
+
position
,
0
)
else
:
self
.
position
=
min
(
self
.
position
+
position
,
self
.
size
)
elif
whence
==
io
.
SEEK_END
:
self
.
position
=
max
(
min
(
self
.
size
+
position
,
self
.
size
),
0
)
else
:
raise
ValueError
(
"Invalid argument"
)
return
self
.
position
def
read
(
self
,
size
=
None
):
"""Read data from the file.
"""
if
size
is
None
:
size
=
self
.
size
-
self
.
position
else
:
size
=
min
(
size
,
self
.
size
-
self
.
position
)
buf
=
b""
while
size
>
0
:
while
True
:
data
,
start
,
stop
,
offset
=
self
.
map
[
self
.
map_index
]
if
start
<=
self
.
position
<
stop
:
break
else
:
self
.
map_index
+=
1
if
self
.
map_index
==
len
(
self
.
map
):
self
.
map_index
=
0
length
=
min
(
size
,
stop
-
self
.
position
)
if
data
:
self
.
fileobj
.
seek
(
offset
+
(
self
.
position
-
start
))
b
=
self
.
fileobj
.
read
(
length
)
if
len
(
b
)
!=
length
:
raise
ReadError
(
"unexpected end of data"
)
buf
+=
b
else
:
buf
+=
NUL
*
length
size
-=
length
self
.
position
+=
length
return
buf
def
readinto
(
self
,
b
):
buf
=
self
.
read
(
len
(
b
))
b
[:
len
(
buf
)]
=
buf
return
len
(
buf
)
def
close
(
self
):
self
.
closed
=
True
#class _FileInFile
class
ExFileObject
(
io
.
BufferedReader
):
def
__init__
(
self
,
tarfile
,
tarinfo
):
fileobj
=
_FileInFile
(
tarfile
.
fileobj
,
tarinfo
.
offset_data
,
tarinfo
.
size
,
tarinfo
.
sparse
)
super
().
__init__
(
fileobj
)
#class ExFileObject
#------------------
# Exported Classes
#------------------
class
TarInfo
(
object
):
"""Informational class which holds the details about an
archive member given by a tar header block.
TarInfo objects are returned by TarFile.getmember(),
TarFile.getmembers() and TarFile.gettarinfo() and are
usually created internally.
"""
__slots__
=
(
"name"
,
"mode"
,
"uid"
,
"gid"
,
"size"
,
"mtime"
,
"chksum"
,
"type"
,
"linkname"
,
"uname"
,
"gname"
,
"devmajor"
,
"devminor"
,
"offset"
,
"offset_data"
,
"pax_headers"
,
"sparse"
,
"tarfile"
,
"_sparse_structs"
,
"_link_target"
)
def
__init__
(
self
,
name
=
""
):
"""Construct a TarInfo object. name is the optional name
of the member.
"""
self
.
name
=
name
# member name
self
.
mode
=
0o644
# file permissions
self
.
uid
=
0
# user id
self
.
gid
=
0
# group id
self
.
size
=
0
# file size
self
.
mtime
=
0
# modification time
self
.
chksum
=
0
# header checksum
self
.
type
=
REGTYPE
# member type
self
.
linkname
=
""
# link name
self
.
uname
=
""
# user name
self
.
gname
=
""
# group name
self
.
devmajor
=
0
# device major number
self
.
devminor
=
0
# device minor number
self
.
offset
=
0
# the tar header starts here
self
.
offset_data
=
0
# the file's data starts here
self
.
sparse
=
None
# sparse member information
self
.
pax_headers
=
{}
# pax header information
# In pax headers the "name" and "linkname" field are called
# "path" and "linkpath".
def
_getpath
(
self
):
return
self
.
name
def
_setpath
(
self
,
name
):
self
.
name
=
name
path
=
property
(
_getpath
,
_setpath
)
def
_getlinkpath
(
self
):
return
self
.
linkname
def
_setlinkpath
(
self
,
linkname
):
self
.
linkname
=
linkname
linkpath
=
property
(
_getlinkpath
,
_setlinkpath
)
def
__repr__
(
self
):
return
"<%s %r at %#x>"
%
(
self
.
__class__
.
__name__
,
self
.
name
,
id
(
self
))
def
get_info
(
self
):
"""Return the TarInfo's attributes as a dictionary.
"""
info
=
{
"name"
:
self
.
name
,
"mode"
:
self
.
mode
&
0o7777
,
"uid"
:
self
.
uid
,
"gid"
:
self
.
gid
,
"size"
:
self
.
size
,
"mtime"
:
self
.
mtime
,
"chksum"
:
self
.
chksum
,
"type"
:
self
.
type
,
"linkname"
:
self
.
linkname
,
"uname"
:
self
.
uname
,
"gname"
:
self
.
gname
,
"devmajor"
:
self
.
devmajor
,
"devminor"
:
self
.
devminor
}
if
info
[
"type"
]
==
DIRTYPE
and
not
info
[
"name"
].
endswith
(
"/"
):
info
[
"name"
]
+=
"/"
return
info
def
tobuf
(
self
,
format
=
DEFAULT_FORMAT
,
encoding
=
ENCODING
,
errors
=
"surrogateescape"
):
"""Return a tar header as a string of 512 byte blocks.
"""
info
=
self
.
get_info
()
if
format
==
USTAR_FORMAT
:
return
self
.
create_ustar_header
(
info
,
encoding
,
errors
)
elif
format
==
GNU_FORMAT
:
return
self
.
create_gnu_header
(
info
,
encoding
,
errors
)
elif
format
==
PAX_FORMAT
:
return
self
.
create_pax_header
(
info
,
encoding
)
else
:
raise
ValueError
(
"invalid format"
)
def
create_ustar_header
(
self
,
info
,
encoding
,
errors
):
"""Return the object as a ustar header block.
"""
info
[
"magic"
]
=
POSIX_MAGIC
if
len
(
info
[
"linkname"
].
encode
(
encoding
,
errors
))
>
LENGTH_LINK
:
raise
ValueError
(
"linkname is too long"
)
if
len
(
info
[
"name"
].
encode
(
encoding
,
errors
))
>
LENGTH_NAME
:
info
[
"prefix"
],
info
[
"name"
]
=
self
.
_posix_split_name
(
info
[
"name"
],
encoding
,
errors
)
return
self
.
_create_header
(
info
,
USTAR_FORMAT
,
encoding
,
errors
)
def
create_gnu_header
(
self
,
info
,
encoding
,
errors
):
"""Return the object as a GNU header block sequence.
"""
info
[
"magic"
]
=
GNU_MAGIC
buf
=
b""
if
len
(
info
[
"linkname"
].
encode
(
encoding
,
errors
))
>
LENGTH_LINK
:
buf
+=
self
.
_create_gnu_long_header
(
info
[
"linkname"
],
GNUTYPE_LONGLINK
,
encoding
,
errors
)
if
len
(
info
[
"name"
].
encode
(
encoding
,
errors
))
>
LENGTH_NAME
:
buf
+=
self
.
_create_gnu_long_header
(
info
[
"name"
],
GNUTYPE_LONGNAME
,
encoding
,
errors
)
return
buf
+
self
.
_create_header
(
info
,
GNU_FORMAT
,
encoding
,
errors
)
def
create_pax_header
(
self
,
info
,
encoding
):
"""Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.
"""
info
[
"magic"
]
=
POSIX_MAGIC
pax_headers
=
self
.
pax_headers
.
copy
()
# Test string fields for values that exceed the field length or cannot
# be represented in ASCII encoding.
for
name
,
hname
,
length
in
(
(
"name"
,
"path"
,
LENGTH_NAME
), (
"linkname"
,
"linkpath"
,
LENGTH_LINK
),
(
"uname"
,
"uname"
,
32
), (
"gname"
,
"gname"
,
32
)):
if
hname
in
pax_headers
:
# The pax header has priority.
continue
# Try to encode the string as ASCII.
try
:
info
[
name
].
encode
(
"ascii"
,
"strict"
)
except
UnicodeEncodeError
:
pax_headers
[
hname
]
=
info
[
name
]
continue
if
len
(
info
[
name
])
>
length
:
pax_headers
[
hname
]
=
info
[
name
]
# Test number fields for values that exceed the field limit or values
# that like to be stored as float.
for
name
,
digits
in
((
"uid"
,
8
), (
"gid"
,
8
), (
"size"
,
12
), (
"mtime"
,
12
)):
if
name
in
pax_headers
:
# The pax header has priority. Avoid overflow.
info
[
name
]
=
0
continue
val
=
info
[
name
]
if
not
0
<=
val
<
8
**
(
digits
-
1
)
or
isinstance
(
val
,
float
):
pax_headers
[
name
]
=
str
(
val
)
info
[
name
]
=
0
# Create a pax extended header if necessary.
if
pax_headers
:
buf
=
self
.
_create_pax_generic_header
(
pax_headers
,
XHDTYPE
,
encoding
)
else
:
buf
=
b""
return
buf
+
self
.
_create_header
(
info
,
USTAR_FORMAT
,
"ascii"
,
"replace"
)
@
classmethod
def
create_pax_global_header
(
cls
,
pax_headers
):
"""Return the object as a pax global header block sequence.
"""
return
cls
.
_create_pax_generic_header
(
pax_headers
,
XGLTYPE
,
"utf-8"
)
def
_posix_split_name
(
self
,
name
,
encoding
,
errors
):
"""Split a name longer than 100 chars into a prefix
and a name part.
"""
components
=
name
.
split
(
"/"
)
for
i
in
range
(
1
,
len
(
components
)):
prefix
=
"/"
.
join
(
components
[:
i
])
name
=
"/"
.
join
(
components
[
i
:])
if
len
(
prefix
.
encode
(
encoding
,
errors
))
<=
LENGTH_PREFIX
and
\
len
(
name
.
encode
(
encoding
,
errors
))
<=
LENGTH_NAME
:
break
else
:
raise
ValueError
(
"name is too long"
)
return
prefix
,
name
@
staticmethod
def
_create_header
(
info
,
format
,
encoding
,
errors
):
"""Return a header block. info is a dictionary with file
information, format must be one of the *_FORMAT constants.
"""
parts
=
[
stn
(
info
.
get
(
"name"
,
""
),
100
,
encoding
,
errors
),
itn
(
info
.
get
(
"mode"
,
0
)
&
0o7777
,
8
,
format
),
itn
(
info
.
get
(
"uid"
,
0
),
8
,
format
),
itn
(
info
.
get
(
"gid"
,
0
),
8
,
format
),
itn
(
info
.
get
(
"size"
,
0
),
12
,
format
),
itn
(
info
.
get
(
"mtime"
,
0
),
12
,
format
),
b" "
,
# checksum field
info
.
get
(
"type"
,
REGTYPE
),
stn
(
info
.
get
(
"linkname"
,
""
),
100
,
encoding
,
errors
),
info
.
get
(
"magic"
,
POSIX_MAGIC
),
stn
(
info
.
get
(
"uname"
,
""
),
32
,
encoding
,
errors
),
stn
(
info
.
get
(
"gname"
,
""
),
32
,
encoding
,
errors
),
itn
(
info
.
get
(
"devmajor"
,
0
),
8
,
format
),
itn
(
info
.
get
(
"devminor"
,
0
),
8
,
format
),
stn
(
info
.
get
(
"prefix"
,
""
),
155
,
encoding
,
errors
)
]
buf
=
struct
.
pack
(
"%ds"
%
BLOCKSIZE
,
b""
.
join
(
parts
))
chksum
=
calc_chksums
(
buf
[
-
BLOCKSIZE
:])[
0
]
buf
=
buf
[:
-
364
]
+
bytes
(
"%06o
\0
"
%
chksum
,
"ascii"
)
+
buf
[
-
357
:]
return
buf
@
staticmethod
def
_create_payload
(
payload
):
"""Return the string payload filled with zero bytes
up to the next 512 byte border.
"""
blocks
,
remainder
=
divmod
(
len
(
payload
),
BLOCKSIZE
)
if
remainder
>
0
:
payload
+=
(
BLOCKSIZE
-
remainder
)
*
NUL
return
payload
@
classmethod
def
_create_gnu_long_header
(
cls
,
name
,
type
,
encoding
,
errors
):
"""Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
for name.
"""
name
=
name
.
encode
(
encoding
,
errors
)
+
NUL
info
=
{}
info
[
"name"
]
=
"././@LongLink"
info
[
"type"
]
=
type
info
[
"size"
]
=
len
(
name
)
info
[
"magic"
]
=
GNU_MAGIC
# create extended header + name blocks.
return
cls
.
_create_header
(
info
,
USTAR_FORMAT
,
encoding
,
errors
)
+
\
cls
.
_create_payload
(
name
)
@
classmethod
def
_create_pax_generic_header
(
cls
,
pax_headers
,
type
,
encoding
):
"""Return a POSIX.1-2008 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be strings.
"""
# Check if one of the fields contains surrogate characters and thereby
# forces hdrcharset=BINARY, see _proc_pax() for more information.
binary
=
False
for
keyword
,
value
in
pax_headers
.
items
():
try
:
value
.
encode
(
"utf-8"
,
"strict"
)
except
UnicodeEncodeError
:
binary
=
True
break
records
=
b""
if
binary
:
# Put the hdrcharset field at the beginning of the header.
records
+=
b"21 hdrcharset=BINARY
\n
"
for
keyword
,
value
in
pax_headers
.
items
():
keyword
=
keyword
.
encode
(
"utf-8"
)
if
binary
:
# Try to restore the original byte representation of `value'.
# Needless to say, that the encoding must match the string.
value
=
value
.
encode
(
encoding
,
"surrogateescape"
)
else
:
value
=
value
.
encode
(
"utf-8"
)
l
=
len
(
keyword
)
+
len
(
value
)
+
3
# ' ' + '=' + '\n'
n
=
p
=
0
while
True
:
n
=
l
+
len
(
str
(
p
))
if
n
==
p
:
break
p
=
n
records
+=
bytes
(
str
(
p
),
"ascii"
)
+
b" "
+
keyword
+
b"="
+
value
+
b"
\n
"
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL