- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathtarfile.py
executable file
·2969 lines (2597 loc) · 107 KB
/
tarfile.py
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\u00e4bel (lars@gustaebel.de)"
__credits__="Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
#---------
# Imports
#---------
frombuiltinsimportopenasbltn_open
importsys
importos
importio
importshutil
importstat
importtime
importstruct
importcopy
importre
try:
importpwd
exceptImportError:
pwd=None
try:
importgrp
exceptImportError:
grp=None
# os.symlink on Windows prior to 6.0 raises NotImplementedError
# OSError (winerror=1314) will be raised if the caller does not hold the
# SeCreateSymbolicLinkPrivilege privilege
symlink_exception= (AttributeError, NotImplementedError, OSError)
# from tarfile import *
__all__= ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError",
"CompressionError", "StreamError", "ExtractError", "HeaderError",
"ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT",
"DEFAULT_FORMAT", "open","fully_trusted_filter", "data_filter",
"tar_filter", "FilterError", "AbsoluteLinkError",
"OutsideDestinationError", "SpecialFileError", "AbsolutePathError",
"LinkOutsideDestinationError"]
#---------------------------------------------------------
# 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\x0000"# 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=PAX_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
#---------------------------------------------------------
ifos.name=="nt":
ENCODING="utf-8"
else:
ENCODING=sys.getfilesystemencoding()
#---------------------------------------------------------
# Some useful functions
#---------------------------------------------------------
defstn(s, length, encoding, errors):
"""Convert a string to a null-terminated bytes object.
"""
ifsisNone:
raiseValueError("metadata cannot contain None")
s=s.encode(encoding, errors)
returns[:length] + (length-len(s)) *NUL
defnts(s, encoding, errors):
"""Convert a null-terminated bytes object to a string.
"""
p=s.find(b"\0")
ifp!=-1:
s=s[:p]
returns.decode(encoding, errors)
defnti(s):
"""Convert a number field to a python number.
"""
# There are two possible encodings for a number field, see
# itn() below.
ifs[0] in (0o200, 0o377):
n=0
foriinrange(len(s) -1):
n<<=8
n+=s[i+1]
ifs[0] ==0o377:
n=-(256** (len(s) -1) -n)
else:
try:
s=nts(s, "ascii", "strict")
n=int(s.strip() or"0", 8)
exceptValueError:
raiseInvalidHeaderError("invalid header")
returnn
defitn(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.
original_n=n
n=int(n)
if0<=n<8** (digits-1):
s=bytes("%0*o"% (digits-1, n), "ascii") +NUL
elifformat==GNU_FORMATand-256** (digits-1) <=n<256** (digits-1):
ifn>=0:
s=bytearray([0o200])
else:
s=bytearray([0o377])
n=256**digits+n
foriinrange(digits-1):
s.insert(1, n&0o377)
n>>=8
else:
raiseValueError("overflow in number field")
returns
defcalc_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))
returnunsigned_chksum, signed_chksum
defcopyfileobj(src, dst, length=None, exception=OSError, bufsize=None):
"""Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content.
"""
bufsize=bufsizeor16*1024
iflength==0:
return
iflengthisNone:
shutil.copyfileobj(src, dst, bufsize)
return
blocks, remainder=divmod(length, bufsize)
forbinrange(blocks):
buf=src.read(bufsize)
iflen(buf) <bufsize:
raiseexception("unexpected end of data")
dst.write(buf)
ifremainder!=0:
buf=src.read(remainder)
iflen(buf) <remainder:
raiseexception("unexpected end of data")
dst.write(buf)
return
def_safe_print(s):
encoding=getattr(sys.stdout, 'encoding', None)
ifencodingisnotNone:
s=s.encode(encoding, 'backslashreplace').decode(encoding)
print(s, end=' ')
classTarError(Exception):
"""Base exception."""
pass
classExtractError(TarError):
"""General exception for extract errors."""
pass
classReadError(TarError):
"""Exception for unreadable tar archives."""
pass
classCompressionError(TarError):
"""Exception for unavailable compression methods."""
pass
classStreamError(TarError):
"""Exception for unsupported operations on stream-like TarFiles."""
pass
classHeaderError(TarError):
"""Base exception for header errors."""
pass
classEmptyHeaderError(HeaderError):
"""Exception for empty headers."""
pass
classTruncatedHeaderError(HeaderError):
"""Exception for truncated headers."""
pass
classEOFHeaderError(HeaderError):
"""Exception for end of file headers."""
pass
classInvalidHeaderError(HeaderError):
"""Exception for invalid headers."""
pass
classSubsequentHeaderError(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]
ifhasattr(os, "O_BINARY"):
mode|=os.O_BINARY
self.fd=os.open(name, mode, 0o666)
defclose(self):
os.close(self.fd)
defread(self, size):
returnos.read(self.fd, size)
defwrite(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 that works with bytes,
and the method is accessed blockwise.
Use of gzip or bzip2 compression is possible.
A stream-like object could be for example: sys.stdin.buffer,
sys.stdout.buffer, a socket, a tape device etc.
_Stream is intended to be used only internally.
"""
def__init__(self, name, mode, comptype, fileobj, bufsize,
compresslevel):
"""Construct a _Stream object.
"""
self._extfileobj=True
iffileobjisNone:
fileobj=_LowLevelFile(name, mode)
self._extfileobj=False
ifcomptype=='*':
# Enable transparent compression detection for the
# stream interface
fileobj=_StreamProxy(fileobj)
comptype=fileobj.getcomptype()
self.name=nameor""
self.mode=mode
self.comptype=comptype
self.fileobj=fileobj
self.bufsize=bufsize
self.buf=b""
self.pos=0
self.closed=False
try:
ifcomptype=="gz":
try:
importzlib
exceptImportError:
raiseCompressionError("zlib module is not available") fromNone
self.zlib=zlib
self.crc=zlib.crc32(b"")
ifmode=="r":
self.exception=zlib.error
self._init_read_gz()
else:
self._init_write_gz(compresslevel)
elifcomptype=="bz2":
try:
importbz2
exceptImportError:
raiseCompressionError("bz2 module is not available") fromNone
ifmode=="r":
self.dbuf=b""
self.cmp=bz2.BZ2Decompressor()
self.exception=OSError
else:
self.cmp=bz2.BZ2Compressor(compresslevel)
elifcomptype=="xz":
try:
importlzma
exceptImportError:
raiseCompressionError("lzma module is not available") fromNone
ifmode=="r":
self.dbuf=b""
self.cmp=lzma.LZMADecompressor()
self.exception=lzma.LZMAError
else:
self.cmp=lzma.LZMACompressor()
elifcomptype!="tar":
raiseCompressionError("unknown compression type %r"%comptype)
except:
ifnotself._extfileobj:
self.fileobj.close()
self.closed=True
raise
def__del__(self):
ifhasattr(self, "closed") andnotself.closed:
self.close()
def_init_write_gz(self, compresslevel):
"""Initialize for writing with gzip compression.
"""
self.cmp=self.zlib.compressobj(compresslevel,
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")
ifself.name.endswith(".gz"):
self.name=self.name[:-3]
# Honor "directory components removed" from RFC1952
self.name=os.path.basename(self.name)
# RFC1952 says we must use ISO-8859-1 for the FNAME field.
self.__write(self.name.encode("iso-8859-1", "replace") +NUL)
defwrite(self, s):
"""Write string s to the stream.
"""
ifself.comptype=="gz":
self.crc=self.zlib.crc32(s, self.crc)
self.pos+=len(s)
ifself.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
whilelen(self.buf) >self.bufsize:
self.fileobj.write(self.buf[:self.bufsize])
self.buf=self.buf[self.bufsize:]
defclose(self):
"""Close the _Stream object. No operation should be
done on it afterwards.
"""
ifself.closed:
return
self.closed=True
try:
ifself.mode=="w"andself.comptype!="tar":
self.buf+=self.cmp.flush()
ifself.mode=="w"andself.buf:
self.fileobj.write(self.buf)
self.buf=b""
ifself.comptype=="gz":
self.fileobj.write(struct.pack("<L", self.crc))
self.fileobj.write(struct.pack("<L", self.pos&0xffffFFFF))
finally:
ifnotself._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
ifself.__read(2) !=b"\037\213":
raiseReadError("not a gzip file")
ifself.__read(1) !=b"\010":
raiseCompressionError("unsupported compression method")
flag=ord(self.__read(1))
self.__read(6)
ifflag&4:
xlen=ord(self.__read(1)) +256*ord(self.__read(1))
self.read(xlen)
ifflag&8:
whileTrue:
s=self.__read(1)
ifnotsors==NUL:
break
ifflag&16:
whileTrue:
s=self.__read(1)
ifnotsors==NUL:
break
ifflag&2:
self.__read(2)
deftell(self):
"""Return the stream's file pointer position.
"""
returnself.pos
defseek(self, pos=0):
"""Set the stream's file pointer to pos. Negative seeking
is forbidden.
"""
ifpos-self.pos>=0:
blocks, remainder=divmod(pos-self.pos, self.bufsize)
foriinrange(blocks):
self.read(self.bufsize)
self.read(remainder)
else:
raiseStreamError("seeking backwards is not allowed")
returnself.pos
defread(self, size):
"""Return the next size number of bytes from the stream."""
assertsizeisnotNone
buf=self._read(size)
self.pos+=len(buf)
returnbuf
def_read(self, size):
"""Return size bytes from the stream.
"""
ifself.comptype=="tar":
returnself.__read(size)
c=len(self.dbuf)
t= [self.dbuf]
whilec<size:
# Skip underlying buffer to avoid unaligned double buffering.
ifself.buf:
buf=self.buf
self.buf=b""
else:
buf=self.fileobj.read(self.bufsize)
ifnotbuf:
break
try:
buf=self.cmp.decompress(buf)
exceptself.exceptionase:
raiseReadError("invalid compressed data") frome
t.append(buf)
c+=len(buf)
t=b"".join(t)
self.dbuf=t[size:]
returnt[:size]
def__read(self, size):
"""Return size bytes from stream. If internal buffer is empty,
read another block from the stream.
"""
c=len(self.buf)
t= [self.buf]
whilec<size:
buf=self.fileobj.read(self.bufsize)
ifnotbuf:
break
t.append(buf)
c+=len(buf)
t=b"".join(t)
self.buf=t[size:]
returnt[:size]
# 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)
defread(self, size):
self.read=self.fileobj.read
returnself.buf
defgetcomptype(self):
ifself.buf.startswith(b"\x1f\x8b\x08"):
return"gz"
elifself.buf[0:3] ==b"BZh"andself.buf[4:10] ==b"1AY&SY":
return"bz2"
elifself.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")):
return"xz"
else:
return"tar"
defclose(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, name, blockinfo=None):
self.fileobj=fileobj
self.offset=offset
self.size=size
self.position=0
self.name=name
self.closed=False
ifblockinfoisNone:
blockinfo= [(0, size)]
# Construct a map with data and zero blocks.
self.map_index=0
self.map= []
lastpos=0
realpos=self.offset
foroffset, sizeinblockinfo:
ifoffset>lastpos:
self.map.append((False, lastpos, offset, None))
self.map.append((True, offset, offset+size, realpos))
realpos+=size
lastpos=offset+size
iflastpos<self.size:
self.map.append((False, lastpos, self.size, None))
defflush(self):
pass
@property
defmode(self):
return'rb'
defreadable(self):
returnTrue
defwritable(self):
returnFalse
defseekable(self):
returnself.fileobj.seekable()
deftell(self):
"""Return the current file position.
"""
returnself.position
defseek(self, position, whence=io.SEEK_SET):
"""Seek to a position in the file.
"""
ifwhence==io.SEEK_SET:
self.position=min(max(position, 0), self.size)
elifwhence==io.SEEK_CUR:
ifposition<0:
self.position=max(self.position+position, 0)
else:
self.position=min(self.position+position, self.size)
elifwhence==io.SEEK_END:
self.position=max(min(self.size+position, self.size), 0)
else:
raiseValueError("Invalid argument")
returnself.position
defread(self, size=None):
"""Read data from the file.
"""
ifsizeisNone:
size=self.size-self.position
else:
size=min(size, self.size-self.position)
buf=b""
whilesize>0:
whileTrue:
data, start, stop, offset=self.map[self.map_index]
ifstart<=self.position<stop:
break
else:
self.map_index+=1
ifself.map_index==len(self.map):
self.map_index=0
length=min(size, stop-self.position)
ifdata:
self.fileobj.seek(offset+ (self.position-start))
b=self.fileobj.read(length)
iflen(b) !=length:
raiseReadError("unexpected end of data")
buf+=b
else:
buf+=NUL*length
size-=length
self.position+=length
returnbuf
defreadinto(self, b):
buf=self.read(len(b))
b[:len(buf)] =buf
returnlen(buf)
defclose(self):
self.closed=True
#class _FileInFile
classExFileObject(io.BufferedReader):
def__init__(self, tarfile, tarinfo):
fileobj=_FileInFile(tarfile.fileobj, tarinfo.offset_data,
tarinfo.size, tarinfo.name, tarinfo.sparse)
super().__init__(fileobj)
#class ExFileObject
#-----------------------------
# extraction filters (PEP 706)
#-----------------------------
classFilterError(TarError):
pass
classAbsolutePathError(FilterError):
def__init__(self, tarinfo):
self.tarinfo=tarinfo
super().__init__(f'member {tarinfo.name!r} has an absolute path')
classOutsideDestinationError(FilterError):
def__init__(self, tarinfo, path):
self.tarinfo=tarinfo
self._path=path
super().__init__(f'{tarinfo.name!r} would be extracted to {path!r}, '
+'which is outside the destination')
classSpecialFileError(FilterError):
def__init__(self, tarinfo):
self.tarinfo=tarinfo
super().__init__(f'{tarinfo.name!r} is a special file')
classAbsoluteLinkError(FilterError):
def__init__(self, tarinfo):
self.tarinfo=tarinfo
super().__init__(f'{tarinfo.name!r} is a link to an absolute path')
classLinkOutsideDestinationError(FilterError):
def__init__(self, tarinfo, path):
self.tarinfo=tarinfo
self._path=path
super().__init__(f'{tarinfo.name!r} would link to {path!r}, '
+'which is outside the destination')
def_get_filtered_attrs(member, dest_path, for_data=True):
new_attrs= {}
name=member.name
dest_path=os.path.realpath(dest_path)
# Strip leading / (tar's directory separator) from filenames.
# Include os.sep (target OS directory separator) as well.
ifname.startswith(('/', os.sep)):
name=new_attrs['name'] =member.path.lstrip('/'+os.sep)
ifos.path.isabs(name):
# Path is absolute even after stripping.
# For example, 'C:/foo' on Windows.
raiseAbsolutePathError(member)
# Ensure we stay in the destination
target_path=os.path.realpath(os.path.join(dest_path, name))
ifos.path.commonpath([target_path, dest_path]) !=dest_path:
raiseOutsideDestinationError(member, target_path)
# Limit permissions (no high bits, and go-w)
mode=member.mode
ifmodeisnotNone:
# Strip high bits & group/other write bits
mode=mode&0o755
iffor_data:
# For data, handle permissions & file types
ifmember.isreg() ormember.islnk():
ifnotmode&0o100:
# Clear executable bits if not executable by user
mode&=~0o111
# Ensure owner can read & write
mode|=0o600
elifmember.isdir() ormember.issym():
# Ignore mode for directories & symlinks
mode=None
else:
# Reject special files
raiseSpecialFileError(member)
ifmode!=member.mode:
new_attrs['mode'] =mode
iffor_data:
# Ignore ownership for 'data'
ifmember.uidisnotNone:
new_attrs['uid'] =None
ifmember.gidisnotNone:
new_attrs['gid'] =None
ifmember.unameisnotNone:
new_attrs['uname'] =None
ifmember.gnameisnotNone:
new_attrs['gname'] =None
# Check link destination for 'data'
ifmember.islnk() ormember.issym():
ifos.path.isabs(member.linkname):
raiseAbsoluteLinkError(member)
ifmember.issym():
target_path=os.path.join(dest_path,
os.path.dirname(name),
member.linkname)
else:
target_path=os.path.join(dest_path,
member.linkname)
target_path=os.path.realpath(target_path)
ifos.path.commonpath([target_path, dest_path]) !=dest_path:
raiseLinkOutsideDestinationError(member, target_path)
returnnew_attrs
deffully_trusted_filter(member, dest_path):
returnmember
deftar_filter(member, dest_path):
new_attrs=_get_filtered_attrs(member, dest_path, False)
ifnew_attrs:
returnmember.replace(**new_attrs, deep=False)
returnmember
defdata_filter(member, dest_path):
new_attrs=_get_filtered_attrs(member, dest_path, True)
ifnew_attrs:
returnmember.replace(**new_attrs, deep=False)
returnmember
_NAMED_FILTERS= {
"fully_trusted": fully_trusted_filter,
"tar": tar_filter,
"data": data_filter,
}
#------------------
# Exported Classes
#------------------
# Sentinel for replace() defaults, meaning "don't change the attribute"
_KEEP=object()
# Header length is digits followed by a space.
_header_length_prefix_re=re.compile(br"([0-9]{1,20}) ")
classTarInfo(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__=dict(
name='Name of the archive member.',
mode='Permission bits.',
uid='User ID of the user who originally stored this member.',
gid='Group ID of the user who originally stored this member.',
size='Size in bytes.',
mtime='Time of last modification.',
chksum='Header checksum.',
type= ('File type. type is usually one of these constants: '
'REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, '
'CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'),
linkname= ('Name of the target file name, which is only present '
'in TarInfo objects of type LNKTYPE and SYMTYPE.'),
uname='User name.',
gname='Group name.',
devmajor='Device major number.',
devminor='Device minor number.',
offset='The tar header starts here.',
offset_data="The file's data starts here.",
pax_headers= ('A dictionary containing key-value pairs of an '
'associated pax extended header.'),
sparse='Sparse member information.',
_tarfile=None,
_sparse_structs=None,
_link_target=None,
)
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
@property
deftarfile(self):
importwarnings
warnings.warn(
'The undocumented "tarfile" attribute of TarInfo objects '
+'is deprecated and will be removed in Python 3.16',
DeprecationWarning, stacklevel=2)
returnself._tarfile
@tarfile.setter
deftarfile(self, tarfile):
importwarnings
warnings.warn(
'The undocumented "tarfile" attribute of TarInfo objects '
+'is deprecated and will be removed in Python 3.16',
DeprecationWarning, stacklevel=2)
self._tarfile=tarfile
@property
defpath(self):
'In pax headers, "name" is called "path".'
returnself.name
@path.setter
defpath(self, name):
self.name=name
@property
deflinkpath(self):
'In pax headers, "linkname" is called "linkpath".'
returnself.linkname
@linkpath.setter
deflinkpath(self, linkname):
self.linkname=linkname
def__repr__(self):
return"<%s %r at %#x>"% (self.__class__.__name__,self.name,id(self))
defreplace(self, *,
name=_KEEP, mtime=_KEEP, mode=_KEEP, linkname=_KEEP,
uid=_KEEP, gid=_KEEP, uname=_KEEP, gname=_KEEP,
deep=True, _KEEP=_KEEP):
"""Return a deep copy of self with the given attributes replaced.
"""
ifdeep:
result=copy.deepcopy(self)
else:
result=copy.copy(self)
ifnameisnot_KEEP:
result.name=name
ifmtimeisnot_KEEP:
result.mtime=mtime
ifmodeisnot_KEEP:
result.mode=mode
iflinknameisnot_KEEP:
result.linkname=linkname
ifuidisnot_KEEP:
result.uid=uid
ifgidisnot_KEEP:
result.gid=gid
ifunameisnot_KEEP:
result.uname=uname
ifgnameisnot_KEEP:
result.gname=gname
returnresult
defget_info(self):
"""Return the TarInfo's attributes as a dictionary.
"""
ifself.modeisNone:
mode=None
else:
mode=self.mode&0o7777
info= {
"name": self.name,
"mode": mode,
"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
}