Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

tarfile.py 90 KB

You have to be logged in to leave a comment. Sign In
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
  1. #!/usr/bin/env python3
  2. #-------------------------------------------------------------------
  3. # tarfile.py
  4. #-------------------------------------------------------------------
  5. # Copyright (C) 2002 Lars Gustaebel <lars@gustaebel.de>
  6. # All rights reserved.
  7. #
  8. # Permission is hereby granted, free of charge, to any person
  9. # obtaining a copy of this software and associated documentation
  10. # files (the "Software"), to deal in the Software without
  11. # restriction, including without limitation the rights to use,
  12. # copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the
  14. # Software is furnished to do so, subject to the following
  15. # conditions:
  16. #
  17. # The above copyright notice and this permission notice shall be
  18. # included in all copies or substantial portions of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  22. # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  24. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  25. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  26. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  27. # OTHER DEALINGS IN THE SOFTWARE.
  28. #
  29. """Read from and write to tar format archives.
  30. """
  31. version = "0.9.0"
  32. __author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)"
  33. __credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
  34. #---------
  35. # Imports
  36. #---------
  37. from builtins import open as bltn_open
  38. import sys
  39. import os
  40. import io
  41. import shutil
  42. import stat
  43. import time
  44. import struct
  45. import copy
  46. import re
  47. try:
  48. import pwd
  49. except ImportError:
  50. pwd = None
  51. try:
  52. import grp
  53. except ImportError:
  54. grp = None
  55. # os.symlink on Windows prior to 6.0 raises NotImplementedError
  56. symlink_exception = (AttributeError, NotImplementedError)
  57. try:
  58. # OSError (winerror=1314) will be raised if the caller does not hold the
  59. # SeCreateSymbolicLinkPrivilege privilege
  60. symlink_exception += (OSError,)
  61. except NameError:
  62. pass
  63. # from tarfile import *
  64. __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError",
  65. "CompressionError", "StreamError", "ExtractError", "HeaderError",
  66. "ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT",
  67. "DEFAULT_FORMAT", "open"]
  68. #---------------------------------------------------------
  69. # tar constants
  70. #---------------------------------------------------------
  71. NUL = b"\0" # the null character
  72. BLOCKSIZE = 512 # length of processing blocks
  73. RECORDSIZE = BLOCKSIZE * 20 # length of records
  74. GNU_MAGIC = b"ustar \0" # magic gnu tar string
  75. POSIX_MAGIC = b"ustar\x0000" # magic posix tar string
  76. LENGTH_NAME = 100 # maximum length of a filename
  77. LENGTH_LINK = 100 # maximum length of a linkname
  78. LENGTH_PREFIX = 155 # maximum length of the prefix field
  79. REGTYPE = b"0" # regular file
  80. AREGTYPE = b"\0" # regular file
  81. LNKTYPE = b"1" # link (inside tarfile)
  82. SYMTYPE = b"2" # symbolic link
  83. CHRTYPE = b"3" # character special device
  84. BLKTYPE = b"4" # block special device
  85. DIRTYPE = b"5" # directory
  86. FIFOTYPE = b"6" # fifo special device
  87. CONTTYPE = b"7" # contiguous file
  88. GNUTYPE_LONGNAME = b"L" # GNU tar longname
  89. GNUTYPE_LONGLINK = b"K" # GNU tar longlink
  90. GNUTYPE_SPARSE = b"S" # GNU tar sparse file
  91. XHDTYPE = b"x" # POSIX.1-2001 extended header
  92. XGLTYPE = b"g" # POSIX.1-2001 global header
  93. SOLARIS_XHDTYPE = b"X" # Solaris extended header
  94. USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format
  95. GNU_FORMAT = 1 # GNU tar format
  96. PAX_FORMAT = 2 # POSIX.1-2001 (pax) format
  97. DEFAULT_FORMAT = GNU_FORMAT
  98. #---------------------------------------------------------
  99. # tarfile constants
  100. #---------------------------------------------------------
  101. # File types that tarfile supports:
  102. SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
  103. SYMTYPE, DIRTYPE, FIFOTYPE,
  104. CONTTYPE, CHRTYPE, BLKTYPE,
  105. GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
  106. GNUTYPE_SPARSE)
  107. # File types that will be treated as a regular file.
  108. REGULAR_TYPES = (REGTYPE, AREGTYPE,
  109. CONTTYPE, GNUTYPE_SPARSE)
  110. # File types that are part of the GNU tar format.
  111. GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
  112. GNUTYPE_SPARSE)
  113. # Fields from a pax header that override a TarInfo attribute.
  114. PAX_FIELDS = ("path", "linkpath", "size", "mtime",
  115. "uid", "gid", "uname", "gname")
  116. # Fields from a pax header that are affected by hdrcharset.
  117. PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"}
  118. # Fields in a pax header that are numbers, all other fields
  119. # are treated as strings.
  120. PAX_NUMBER_FIELDS = {
  121. "atime": float,
  122. "ctime": float,
  123. "mtime": float,
  124. "uid": int,
  125. "gid": int,
  126. "size": int
  127. }
  128. #---------------------------------------------------------
  129. # initialization
  130. #---------------------------------------------------------
  131. if os.name == "nt":
  132. ENCODING = "utf-8"
  133. else:
  134. ENCODING = sys.getfilesystemencoding()
  135. #---------------------------------------------------------
  136. # Some useful functions
  137. #---------------------------------------------------------
  138. def stn(s, length, encoding, errors):
  139. """Convert a string to a null-terminated bytes object.
  140. """
  141. s = s.encode(encoding, errors)
  142. return s[:length] + (length - len(s)) * NUL
  143. def nts(s, encoding, errors):
  144. """Convert a null-terminated bytes object to a string.
  145. """
  146. p = s.find(b"\0")
  147. if p != -1:
  148. s = s[:p]
  149. return s.decode(encoding, errors)
  150. def nti(s):
  151. """Convert a number field to a python number.
  152. """
  153. # There are two possible encodings for a number field, see
  154. # itn() below.
  155. if s[0] in (0o200, 0o377):
  156. n = 0
  157. for i in range(len(s) - 1):
  158. n <<= 8
  159. n += s[i + 1]
  160. if s[0] == 0o377:
  161. n = -(256 ** (len(s) - 1) - n)
  162. else:
  163. try:
  164. s = nts(s, "ascii", "strict")
  165. n = int(s.strip() or "0", 8)
  166. except ValueError:
  167. raise InvalidHeaderError("invalid header")
  168. return n
  169. def itn(n, digits=8, format=DEFAULT_FORMAT):
  170. """Convert a python number to a number field.
  171. """
  172. # POSIX 1003.1-1988 requires numbers to be encoded as a string of
  173. # octal digits followed by a null-byte, this allows values up to
  174. # (8**(digits-1))-1. GNU tar allows storing numbers greater than
  175. # that if necessary. A leading 0o200 or 0o377 byte indicate this
  176. # particular encoding, the following digits-1 bytes are a big-endian
  177. # base-256 representation. This allows values up to (256**(digits-1))-1.
  178. # A 0o200 byte indicates a positive number, a 0o377 byte a negative
  179. # number.
  180. n = int(n)
  181. if 0 <= n < 8 ** (digits - 1):
  182. s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL
  183. elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1):
  184. if n >= 0:
  185. s = bytearray([0o200])
  186. else:
  187. s = bytearray([0o377])
  188. n = 256 ** digits + n
  189. for i in range(digits - 1):
  190. s.insert(1, n & 0o377)
  191. n >>= 8
  192. else:
  193. raise ValueError("overflow in number field")
  194. return s
  195. def calc_chksums(buf):
  196. """Calculate the checksum for a member's header by summing up all
  197. characters except for the chksum field which is treated as if
  198. it was filled with spaces. According to the GNU tar sources,
  199. some tars (Sun and NeXT) calculate chksum with signed char,
  200. which will be different if there are chars in the buffer with
  201. the high bit set. So we calculate two checksums, unsigned and
  202. signed.
  203. """
  204. unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
  205. signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
  206. return unsigned_chksum, signed_chksum
  207. def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None):
  208. """Copy length bytes from fileobj src to fileobj dst.
  209. If length is None, copy the entire content.
  210. """
  211. bufsize = bufsize or 16 * 1024
  212. if length == 0:
  213. return
  214. if length is None:
  215. shutil.copyfileobj(src, dst, bufsize)
  216. return
  217. blocks, remainder = divmod(length, bufsize)
  218. for b in range(blocks):
  219. buf = src.read(bufsize)
  220. if len(buf) < bufsize:
  221. raise exception("unexpected end of data")
  222. dst.write(buf)
  223. if remainder != 0:
  224. buf = src.read(remainder)
  225. if len(buf) < remainder:
  226. raise exception("unexpected end of data")
  227. dst.write(buf)
  228. return
  229. def filemode(mode):
  230. """Deprecated in this location; use stat.filemode."""
  231. import warnings
  232. warnings.warn("deprecated in favor of stat.filemode",
  233. DeprecationWarning, 2)
  234. return stat.filemode(mode)
  235. def _safe_print(s):
  236. encoding = getattr(sys.stdout, 'encoding', None)
  237. if encoding is not None:
  238. s = s.encode(encoding, 'backslashreplace').decode(encoding)
  239. print(s, end=' ')
  240. class TarError(Exception):
  241. """Base exception."""
  242. pass
  243. class ExtractError(TarError):
  244. """General exception for extract errors."""
  245. pass
  246. class ReadError(TarError):
  247. """Exception for unreadable tar archives."""
  248. pass
  249. class CompressionError(TarError):
  250. """Exception for unavailable compression methods."""
  251. pass
  252. class StreamError(TarError):
  253. """Exception for unsupported operations on stream-like TarFiles."""
  254. pass
  255. class HeaderError(TarError):
  256. """Base exception for header errors."""
  257. pass
  258. class EmptyHeaderError(HeaderError):
  259. """Exception for empty headers."""
  260. pass
  261. class TruncatedHeaderError(HeaderError):
  262. """Exception for truncated headers."""
  263. pass
  264. class EOFHeaderError(HeaderError):
  265. """Exception for end of file headers."""
  266. pass
  267. class InvalidHeaderError(HeaderError):
  268. """Exception for invalid headers."""
  269. pass
  270. class SubsequentHeaderError(HeaderError):
  271. """Exception for missing and invalid extended headers."""
  272. pass
  273. #---------------------------
  274. # internal stream interface
  275. #---------------------------
  276. class _LowLevelFile:
  277. """Low-level file object. Supports reading and writing.
  278. It is used instead of a regular file object for streaming
  279. access.
  280. """
  281. def __init__(self, name, mode):
  282. mode = {
  283. "r": os.O_RDONLY,
  284. "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
  285. }[mode]
  286. if hasattr(os, "O_BINARY"):
  287. mode |= os.O_BINARY
  288. self.fd = os.open(name, mode, 0o666)
  289. def close(self):
  290. os.close(self.fd)
  291. def read(self, size):
  292. return os.read(self.fd, size)
  293. def write(self, s):
  294. os.write(self.fd, s)
  295. class _Stream:
  296. """Class that serves as an adapter between TarFile and
  297. a stream-like object. The stream-like object only
  298. needs to have a read() or write() method and is accessed
  299. blockwise. Use of gzip or bzip2 compression is possible.
  300. A stream-like object could be for example: sys.stdin,
  301. sys.stdout, a socket, a tape device etc.
  302. _Stream is intended to be used only internally.
  303. """
  304. def __init__(self, name, mode, comptype, fileobj, bufsize):
  305. """Construct a _Stream object.
  306. """
  307. self._extfileobj = True
  308. if fileobj is None:
  309. fileobj = _LowLevelFile(name, mode)
  310. self._extfileobj = False
  311. if comptype == '*':
  312. # Enable transparent compression detection for the
  313. # stream interface
  314. fileobj = _StreamProxy(fileobj)
  315. comptype = fileobj.getcomptype()
  316. self.name = name or ""
  317. self.mode = mode
  318. self.comptype = comptype
  319. self.fileobj = fileobj
  320. self.bufsize = bufsize
  321. self.buf = b""
  322. self.pos = 0
  323. self.closed = False
  324. try:
  325. if comptype == "gz":
  326. try:
  327. import zlib
  328. except ImportError:
  329. raise CompressionError("zlib module is not available")
  330. self.zlib = zlib
  331. self.crc = zlib.crc32(b"")
  332. if mode == "r":
  333. self._init_read_gz()
  334. self.exception = zlib.error
  335. else:
  336. self._init_write_gz()
  337. elif comptype == "bz2":
  338. try:
  339. import bz2
  340. except ImportError:
  341. raise CompressionError("bz2 module is not available")
  342. if mode == "r":
  343. self.dbuf = b""
  344. self.cmp = bz2.BZ2Decompressor()
  345. self.exception = OSError
  346. else:
  347. self.cmp = bz2.BZ2Compressor()
  348. elif comptype == "xz":
  349. try:
  350. import lzma
  351. except ImportError:
  352. raise CompressionError("lzma module is not available")
  353. if mode == "r":
  354. self.dbuf = b""
  355. self.cmp = lzma.LZMADecompressor()
  356. self.exception = lzma.LZMAError
  357. else:
  358. self.cmp = lzma.LZMACompressor()
  359. elif comptype != "tar":
  360. raise CompressionError("unknown compression type %r" % comptype)
  361. except:
  362. if not self._extfileobj:
  363. self.fileobj.close()
  364. self.closed = True
  365. raise
  366. def __del__(self):
  367. if hasattr(self, "closed") and not self.closed:
  368. self.close()
  369. def _init_write_gz(self):
  370. """Initialize for writing with gzip compression.
  371. """
  372. self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED,
  373. -self.zlib.MAX_WBITS,
  374. self.zlib.DEF_MEM_LEVEL,
  375. 0)
  376. timestamp = struct.pack("<L", int(time.time()))
  377. self.__write(b"\037\213\010\010" + timestamp + b"\002\377")
  378. if self.name.endswith(".gz"):
  379. self.name = self.name[:-3]
  380. # RFC1952 says we must use ISO-8859-1 for the FNAME field.
  381. self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
  382. def write(self, s):
  383. """Write string s to the stream.
  384. """
  385. if self.comptype == "gz":
  386. self.crc = self.zlib.crc32(s, self.crc)
  387. self.pos += len(s)
  388. if self.comptype != "tar":
  389. s = self.cmp.compress(s)
  390. self.__write(s)
  391. def __write(self, s):
  392. """Write string s to the stream if a whole new block
  393. is ready to be written.
  394. """
  395. self.buf += s
  396. while len(self.buf) > self.bufsize:
  397. self.fileobj.write(self.buf[:self.bufsize])
  398. self.buf = self.buf[self.bufsize:]
  399. def close(self):
  400. """Close the _Stream object. No operation should be
  401. done on it afterwards.
  402. """
  403. if self.closed:
  404. return
  405. self.closed = True
  406. try:
  407. if self.mode == "w" and self.comptype != "tar":
  408. self.buf += self.cmp.flush()
  409. if self.mode == "w" and self.buf:
  410. self.fileobj.write(self.buf)
  411. self.buf = b""
  412. if self.comptype == "gz":
  413. self.fileobj.write(struct.pack("<L", self.crc))
  414. self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF))
  415. finally:
  416. if not self._extfileobj:
  417. self.fileobj.close()
  418. def _init_read_gz(self):
  419. """Initialize for reading a gzip compressed fileobj.
  420. """
  421. self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
  422. self.dbuf = b""
  423. # taken from gzip.GzipFile with some alterations
  424. if self.__read(2) != b"\037\213":
  425. raise ReadError("not a gzip file")
  426. if self.__read(1) != b"\010":
  427. raise CompressionError("unsupported compression method")
  428. flag = ord(self.__read(1))
  429. self.__read(6)
  430. if flag & 4:
  431. xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
  432. self.read(xlen)
  433. if flag & 8:
  434. while True:
  435. s = self.__read(1)
  436. if not s or s == NUL:
  437. break
  438. if flag & 16:
  439. while True:
  440. s = self.__read(1)
  441. if not s or s == NUL:
  442. break
  443. if flag & 2:
  444. self.__read(2)
  445. def tell(self):
  446. """Return the stream's file pointer position.
  447. """
  448. return self.pos
  449. def seek(self, pos=0):
  450. """Set the stream's file pointer to pos. Negative seeking
  451. is forbidden.
  452. """
  453. if pos - self.pos >= 0:
  454. blocks, remainder = divmod(pos - self.pos, self.bufsize)
  455. for i in range(blocks):
  456. self.read(self.bufsize)
  457. self.read(remainder)
  458. else:
  459. raise StreamError("seeking backwards is not allowed")
  460. return self.pos
  461. def read(self, size=None):
  462. """Return the next size number of bytes from the stream.
  463. If size is not defined, return all bytes of the stream
  464. up to EOF.
  465. """
  466. if size is None:
  467. t = []
  468. while True:
  469. buf = self._read(self.bufsize)
  470. if not buf:
  471. break
  472. t.append(buf)
  473. buf = b"".join(t)
  474. else:
  475. buf = self._read(size)
  476. self.pos += len(buf)
  477. return buf
  478. def _read(self, size):
  479. """Return size bytes from the stream.
  480. """
  481. if self.comptype == "tar":
  482. return self.__read(size)
  483. c = len(self.dbuf)
  484. t = [self.dbuf]
  485. while c < size:
  486. buf = self.__read(self.bufsize)
  487. if not buf:
  488. break
  489. try:
  490. buf = self.cmp.decompress(buf)
  491. except self.exception:
  492. raise ReadError("invalid compressed data")
  493. t.append(buf)
  494. c += len(buf)
  495. t = b"".join(t)
  496. self.dbuf = t[size:]
  497. return t[:size]
  498. def __read(self, size):
  499. """Return size bytes from stream. If internal buffer is empty,
  500. read another block from the stream.
  501. """
  502. c = len(self.buf)
  503. t = [self.buf]
  504. while c < size:
  505. buf = self.fileobj.read(self.bufsize)
  506. if not buf:
  507. break
  508. t.append(buf)
  509. c += len(buf)
  510. t = b"".join(t)
  511. self.buf = t[size:]
  512. return t[:size]
  513. # class _Stream
  514. class _StreamProxy(object):
  515. """Small proxy class that enables transparent compression
  516. detection for the Stream interface (mode 'r|*').
  517. """
  518. def __init__(self, fileobj):
  519. self.fileobj = fileobj
  520. self.buf = self.fileobj.read(BLOCKSIZE)
  521. def read(self, size):
  522. self.read = self.fileobj.read
  523. return self.buf
  524. def getcomptype(self):
  525. if self.buf.startswith(b"\x1f\x8b\x08"):
  526. return "gz"
  527. elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY":
  528. return "bz2"
  529. elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")):
  530. return "xz"
  531. else:
  532. return "tar"
  533. def close(self):
  534. self.fileobj.close()
  535. # class StreamProxy
  536. #------------------------
  537. # Extraction file object
  538. #------------------------
  539. class _FileInFile(object):
  540. """A thin wrapper around an existing file object that
  541. provides a part of its data as an individual file
  542. object.
  543. """
  544. def __init__(self, fileobj, offset, size, blockinfo=None):
  545. self.fileobj = fileobj
  546. self.offset = offset
  547. self.size = size
  548. self.position = 0
  549. self.name = getattr(fileobj, "name", None)
  550. self.closed = False
  551. if blockinfo is None:
  552. blockinfo = [(0, size)]
  553. # Construct a map with data and zero blocks.
  554. self.map_index = 0
  555. self.map = []
  556. lastpos = 0
  557. realpos = self.offset
  558. for offset, size in blockinfo:
  559. if offset > lastpos:
  560. self.map.append((False, lastpos, offset, None))
  561. self.map.append((True, offset, offset + size, realpos))
  562. realpos += size
  563. lastpos = offset + size
  564. if lastpos < self.size:
  565. self.map.append((False, lastpos, self.size, None))
  566. def flush(self):
  567. pass
  568. def readable(self):
  569. return True
  570. def writable(self):
  571. return False
  572. def seekable(self):
  573. return self.fileobj.seekable()
  574. def tell(self):
  575. """Return the current file position.
  576. """
  577. return self.position
  578. def seek(self, position, whence=io.SEEK_SET):
  579. """Seek to a position in the file.
  580. """
  581. if whence == io.SEEK_SET:
  582. self.position = min(max(position, 0), self.size)
  583. elif whence == io.SEEK_CUR:
  584. if position < 0:
  585. self.position = max(self.position + position, 0)
  586. else:
  587. self.position = min(self.position + position, self.size)
  588. elif whence == io.SEEK_END:
  589. self.position = max(min(self.size + position, self.size), 0)
  590. else:
  591. raise ValueError("Invalid argument")
  592. return self.position
  593. def read(self, size=None):
  594. """Read data from the file.
  595. """
  596. if size is None:
  597. size = self.size - self.position
  598. else:
  599. size = min(size, self.size - self.position)
  600. buf = b""
  601. while size > 0:
  602. while True:
  603. data, start, stop, offset = self.map[self.map_index]
  604. if start <= self.position < stop:
  605. break
  606. else:
  607. self.map_index += 1
  608. if self.map_index == len(self.map):
  609. self.map_index = 0
  610. length = min(size, stop - self.position)
  611. if data:
  612. self.fileobj.seek(offset + (self.position - start))
  613. b = self.fileobj.read(length)
  614. if len(b) != length:
  615. raise ReadError("unexpected end of data")
  616. buf += b
  617. else:
  618. buf += NUL * length
  619. size -= length
  620. self.position += length
  621. return buf
  622. def readinto(self, b):
  623. buf = self.read(len(b))
  624. b[:len(buf)] = buf
  625. return len(buf)
  626. def close(self):
  627. self.closed = True
  628. #class _FileInFile
  629. class ExFileObject(io.BufferedReader):
  630. def __init__(self, tarfile, tarinfo):
  631. fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data,
  632. tarinfo.size, tarinfo.sparse)
  633. super().__init__(fileobj)
  634. #class ExFileObject
  635. #------------------
  636. # Exported Classes
  637. #------------------
  638. class TarInfo(object):
  639. """Informational class which holds the details about an
  640. archive member given by a tar header block.
  641. TarInfo objects are returned by TarFile.getmember(),
  642. TarFile.getmembers() and TarFile.gettarinfo() and are
  643. usually created internally.
  644. """
  645. __slots__ = ("name", "mode", "uid", "gid", "size", "mtime",
  646. "chksum", "type", "linkname", "uname", "gname",
  647. "devmajor", "devminor",
  648. "offset", "offset_data", "pax_headers", "sparse",
  649. "tarfile", "_sparse_structs", "_link_target")
  650. def __init__(self, name=""):
  651. """Construct a TarInfo object. name is the optional name
  652. of the member.
  653. """
  654. self.name = name # member name
  655. self.mode = 0o644 # file permissions
  656. self.uid = 0 # user id
  657. self.gid = 0 # group id
  658. self.size = 0 # file size
  659. self.mtime = 0 # modification time
  660. self.chksum = 0 # header checksum
  661. self.type = REGTYPE # member type
  662. self.linkname = "" # link name
  663. self.uname = "" # user name
  664. self.gname = "" # group name
  665. self.devmajor = 0 # device major number
  666. self.devminor = 0 # device minor number
  667. self.offset = 0 # the tar header starts here
  668. self.offset_data = 0 # the file's data starts here
  669. self.sparse = None # sparse member information
  670. self.pax_headers = {} # pax header information
  671. # In pax headers the "name" and "linkname" field are called
  672. # "path" and "linkpath".
  673. @property
  674. def path(self):
  675. return self.name
  676. @path.setter
  677. def path(self, name):
  678. self.name = name
  679. @property
  680. def linkpath(self):
  681. return self.linkname
  682. @linkpath.setter
  683. def linkpath(self, linkname):
  684. self.linkname = linkname
  685. def __repr__(self):
  686. return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
  687. def get_info(self):
  688. """Return the TarInfo's attributes as a dictionary.
  689. """
  690. info = {
  691. "name": self.name,
  692. "mode": self.mode & 0o7777,
  693. "uid": self.uid,
  694. "gid": self.gid,
  695. "size": self.size,
  696. "mtime": self.mtime,
  697. "chksum": self.chksum,
  698. "type": self.type,
  699. "linkname": self.linkname,
  700. "uname": self.uname,
  701. "gname": self.gname,
  702. "devmajor": self.devmajor,
  703. "devminor": self.devminor
  704. }
  705. if info["type"] == DIRTYPE and not info["name"].endswith("/"):
  706. info["name"] += "/"
  707. return info
  708. def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
  709. """Return a tar header as a string of 512 byte blocks.
  710. """
  711. info = self.get_info()
  712. if format == USTAR_FORMAT:
  713. return self.create_ustar_header(info, encoding, errors)
  714. elif format == GNU_FORMAT:
  715. return self.create_gnu_header(info, encoding, errors)
  716. elif format == PAX_FORMAT:
  717. return self.create_pax_header(info, encoding)
  718. else:
  719. raise ValueError("invalid format")
  720. def create_ustar_header(self, info, encoding, errors):
  721. """Return the object as a ustar header block.
  722. """
  723. info["magic"] = POSIX_MAGIC
  724. if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
  725. raise ValueError("linkname is too long")
  726. if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
  727. info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors)
  728. return self._create_header(info, USTAR_FORMAT, encoding, errors)
  729. def create_gnu_header(self, info, encoding, errors):
  730. """Return the object as a GNU header block sequence.
  731. """
  732. info["magic"] = GNU_MAGIC
  733. buf = b""
  734. if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
  735. buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
  736. if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
  737. buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
  738. return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
  739. def create_pax_header(self, info, encoding):
  740. """Return the object as a ustar header block. If it cannot be
  741. represented this way, prepend a pax extended header sequence
  742. with supplement information.
  743. """
  744. info["magic"] = POSIX_MAGIC
  745. pax_headers = self.pax_headers.copy()
  746. # Test string fields for values that exceed the field length or cannot
  747. # be represented in ASCII encoding.
  748. for name, hname, length in (
  749. ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
  750. ("uname", "uname", 32), ("gname", "gname", 32)):
  751. if hname in pax_headers:
  752. # The pax header has priority.
  753. continue
  754. # Try to encode the string as ASCII.
  755. try:
  756. info[name].encode("ascii", "strict")
  757. except UnicodeEncodeError:
  758. pax_headers[hname] = info[name]
  759. continue
  760. if len(info[name]) > length:
  761. pax_headers[hname] = info[name]
  762. # Test number fields for values that exceed the field limit or values
  763. # that like to be stored as float.
  764. for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
  765. if name in pax_headers:
  766. # The pax header has priority. Avoid overflow.
  767. info[name] = 0
  768. continue
  769. val = info[name]
  770. if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float):
  771. pax_headers[name] = str(val)
  772. info[name] = 0
  773. # Create a pax extended header if necessary.
  774. if pax_headers:
  775. buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
  776. else:
  777. buf = b""
  778. return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
  779. @classmethod
  780. def create_pax_global_header(cls, pax_headers):
  781. """Return the object as a pax global header block sequence.
  782. """
  783. return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8")
  784. def _posix_split_name(self, name, encoding, errors):
  785. """Split a name longer than 100 chars into a prefix
  786. and a name part.
  787. """
  788. components = name.split("/")
  789. for i in range(1, len(components)):
  790. prefix = "/".join(components[:i])
  791. name = "/".join(components[i:])
  792. if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \
  793. len(name.encode(encoding, errors)) <= LENGTH_NAME:
  794. break
  795. else:
  796. raise ValueError("name is too long")
  797. return prefix, name
  798. @staticmethod
  799. def _create_header(info, format, encoding, errors):
  800. """Return a header block. info is a dictionary with file
  801. information, format must be one of the *_FORMAT constants.
  802. """
  803. parts = [
  804. stn(info.get("name", ""), 100, encoding, errors),
  805. itn(info.get("mode", 0) & 0o7777, 8, format),
  806. itn(info.get("uid", 0), 8, format),
  807. itn(info.get("gid", 0), 8, format),
  808. itn(info.get("size", 0), 12, format),
  809. itn(info.get("mtime", 0), 12, format),
  810. b" ", # checksum field
  811. info.get("type", REGTYPE),
  812. stn(info.get("linkname", ""), 100, encoding, errors),
  813. info.get("magic", POSIX_MAGIC),
  814. stn(info.get("uname", ""), 32, encoding, errors),
  815. stn(info.get("gname", ""), 32, encoding, errors),
  816. itn(info.get("devmajor", 0), 8, format),
  817. itn(info.get("devminor", 0), 8, format),
  818. stn(info.get("prefix", ""), 155, encoding, errors)
  819. ]
  820. buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
  821. chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
  822. buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:]
  823. return buf
  824. @staticmethod
  825. def _create_payload(payload):
  826. """Return the string payload filled with zero bytes
  827. up to the next 512 byte border.
  828. """
  829. blocks, remainder = divmod(len(payload), BLOCKSIZE)
  830. if remainder > 0:
  831. payload += (BLOCKSIZE - remainder) * NUL
  832. return payload
  833. @classmethod
  834. def _create_gnu_long_header(cls, name, type, encoding, errors):
  835. """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
  836. for name.
  837. """
  838. name = name.encode(encoding, errors) + NUL
  839. info = {}
  840. info["name"] = "././@LongLink"
  841. info["type"] = type
  842. info["size"] = len(name)
  843. info["magic"] = GNU_MAGIC
  844. # create extended header + name blocks.
  845. return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
  846. cls._create_payload(name)
  847. @classmethod
  848. def _create_pax_generic_header(cls, pax_headers, type, encoding):
  849. """Return a POSIX.1-2008 extended or global header sequence
  850. that contains a list of keyword, value pairs. The values
  851. must be strings.
  852. """
  853. # Check if one of the fields contains surrogate characters and thereby
  854. # forces hdrcharset=BINARY, see _proc_pax() for more information.
  855. binary = False
  856. for keyword, value in pax_headers.items():
  857. try:
  858. value.encode("utf-8", "strict")
  859. except UnicodeEncodeError:
  860. binary = True
  861. break
  862. records = b""
  863. if binary:
  864. # Put the hdrcharset field at the beginning of the header.
  865. records += b"21 hdrcharset=BINARY\n"
  866. for keyword, value in pax_headers.items():
  867. keyword = keyword.encode("utf-8")
  868. if binary:
  869. # Try to restore the original byte representation of `value'.
  870. # Needless to say, that the encoding must match the string.
  871. value = value.encode(encoding, "surrogateescape")
  872. else:
  873. value = value.encode("utf-8")
  874. l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n'
  875. n = p = 0
  876. while True:
  877. n = l + len(str(p))
  878. if n == p:
  879. break
  880. p = n
  881. records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"
  882. # We use a hardcoded "././@PaxHeader" name like star does
  883. # instead of the one that POSIX recommends.
  884. info = {}
  885. info["name"] = "././@PaxHeader"
  886. info["type"] = type
  887. info["size"] = len(records)
  888. info["magic"] = POSIX_MAGIC
  889. # Create pax header + record blocks.
  890. return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
  891. cls._create_payload(records)
  892. @classmethod
  893. def frombuf(cls, buf, encoding, errors):
  894. """Construct a TarInfo object from a 512 byte bytes object.
  895. """
  896. if len(buf) == 0:
  897. raise EmptyHeaderError("empty header")
  898. if len(buf) != BLOCKSIZE:
  899. raise TruncatedHeaderError("truncated header")
  900. if buf.count(NUL) == BLOCKSIZE:
  901. raise EOFHeaderError("end of file header")
  902. chksum = nti(buf[148:156])
  903. if chksum not in calc_chksums(buf):
  904. raise InvalidHeaderError("bad checksum")
  905. obj = cls()
  906. obj.name = nts(buf[0:100], encoding, errors)
  907. obj.mode = nti(buf[100:108])
  908. obj.uid = nti(buf[108:116])
  909. obj.gid = nti(buf[116:124])
  910. obj.size = nti(buf[124:136])
  911. obj.mtime = nti(buf[136:148])
  912. obj.chksum = chksum
  913. obj.type = buf[156:157]
  914. obj.linkname = nts(buf[157:257], encoding, errors)
  915. obj.uname = nts(buf[265:297], encoding, errors)
  916. obj.gname = nts(buf[297:329], encoding, errors)
  917. obj.devmajor = nti(buf[329:337])
  918. obj.devminor = nti(buf[337:345])
  919. prefix = nts(buf[345:500], encoding, errors)
  920. # Old V7 tar format represents a directory as a regular
  921. # file with a trailing slash.
  922. if obj.type == AREGTYPE and obj.name.endswith("/"):
  923. obj.type = DIRTYPE
  924. # The old GNU sparse format occupies some of the unused
  925. # space in the buffer for up to 4 sparse structures.
  926. # Save them for later processing in _proc_sparse().
  927. if obj.type == GNUTYPE_SPARSE:
  928. pos = 386
  929. structs = []
  930. for i in range(4):
  931. try:
  932. offset = nti(buf[pos:pos + 12])
  933. numbytes = nti(buf[pos + 12:pos + 24])
  934. except ValueError:
  935. break
  936. structs.append((offset, numbytes))
  937. pos += 24
  938. isextended = bool(buf[482])
  939. origsize = nti(buf[483:495])
  940. obj._sparse_structs = (structs, isextended, origsize)
  941. # Remove redundant slashes from directories.
  942. if obj.isdir():
  943. obj.name = obj.name.rstrip("/")
  944. # Reconstruct a ustar longname.
  945. if prefix and obj.type not in GNU_TYPES:
  946. obj.name = prefix + "/" + obj.name
  947. return obj
  948. @classmethod
  949. def fromtarfile(cls, tarfile):
  950. """Return the next TarInfo object from TarFile object
  951. tarfile.
  952. """
  953. buf = tarfile.fileobj.read(BLOCKSIZE)
  954. obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
  955. obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
  956. return obj._proc_member(tarfile)
  957. #--------------------------------------------------------------------------
  958. # The following are methods that are called depending on the type of a
  959. # member. The entry point is _proc_member() which can be overridden in a
  960. # subclass to add custom _proc_*() methods. A _proc_*() method MUST
  961. # implement the following
  962. # operations:
  963. # 1. Set self.offset_data to the position where the data blocks begin,
  964. # if there is data that follows.
  965. # 2. Set tarfile.offset to the position where the next member's header will
  966. # begin.
  967. # 3. Return self or another valid TarInfo object.
  968. def _proc_member(self, tarfile):
  969. """Choose the right processing method depending on
  970. the type and call it.
  971. """
  972. if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
  973. return self._proc_gnulong(tarfile)
  974. elif self.type == GNUTYPE_SPARSE:
  975. return self._proc_sparse(tarfile)
  976. elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
  977. return self._proc_pax(tarfile)
  978. else:
  979. return self._proc_builtin(tarfile)
  980. def _proc_builtin(self, tarfile):
  981. """Process a builtin type or an unknown type which
  982. will be treated as a regular file.
  983. """
  984. self.offset_data = tarfile.fileobj.tell()
  985. offset = self.offset_data
  986. if self.isreg() or self.type not in SUPPORTED_TYPES:
  987. # Skip the following data blocks.
  988. offset += self._block(self.size)
  989. tarfile.offset = offset
  990. # Patch the TarInfo object with saved global
  991. # header information.
  992. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
  993. return self
  994. def _proc_gnulong(self, tarfile):
  995. """Process the blocks that hold a GNU longname
  996. or longlink member.
  997. """
  998. buf = tarfile.fileobj.read(self._block(self.size))
  999. # Fetch the next header and process it.
  1000. try:
  1001. next = self.fromtarfile(tarfile)
  1002. except HeaderError:
  1003. raise SubsequentHeaderError("missing or bad subsequent header")
  1004. # Patch the TarInfo object from the next header with
  1005. # the longname information.
  1006. next.offset = self.offset
  1007. if self.type == GNUTYPE_LONGNAME:
  1008. next.name = nts(buf, tarfile.encoding, tarfile.errors)
  1009. elif self.type == GNUTYPE_LONGLINK:
  1010. next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
  1011. return next
  1012. def _proc_sparse(self, tarfile):
  1013. """Process a GNU sparse header plus extra headers.
  1014. """
  1015. # We already collected some sparse structures in frombuf().
  1016. structs, isextended, origsize = self._sparse_structs
  1017. del self._sparse_structs
  1018. # Collect sparse structures from extended header blocks.
  1019. while isextended:
  1020. buf = tarfile.fileobj.read(BLOCKSIZE)
  1021. pos = 0
  1022. for i in range(21):
  1023. try:
  1024. offset = nti(buf[pos:pos + 12])
  1025. numbytes = nti(buf[pos + 12:pos + 24])
  1026. except ValueError:
  1027. break
  1028. if offset and numbytes:
  1029. structs.append((offset, numbytes))
  1030. pos += 24
  1031. isextended = bool(buf[504])
  1032. self.sparse = structs
  1033. self.offset_data = tarfile.fileobj.tell()
  1034. tarfile.offset = self.offset_data + self._block(self.size)
  1035. self.size = origsize
  1036. return self
  1037. def _proc_pax(self, tarfile):
  1038. """Process an extended or global header as described in
  1039. POSIX.1-2008.
  1040. """
  1041. # Read the header information.
  1042. buf = tarfile.fileobj.read(self._block(self.size))
  1043. # A pax header stores supplemental information for either
  1044. # the following file (extended) or all following files
  1045. # (global).
  1046. if self.type == XGLTYPE:
  1047. pax_headers = tarfile.pax_headers
  1048. else:
  1049. pax_headers = tarfile.pax_headers.copy()
  1050. # Check if the pax header contains a hdrcharset field. This tells us
  1051. # the encoding of the path, linkpath, uname and gname fields. Normally,
  1052. # these fields are UTF-8 encoded but since POSIX.1-2008 tar
  1053. # implementations are allowed to store them as raw binary strings if
  1054. # the translation to UTF-8 fails.
  1055. match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
  1056. if match is not None:
  1057. pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
  1058. # For the time being, we don't care about anything other than "BINARY".
  1059. # The only other value that is currently allowed by the standard is
  1060. # "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
  1061. hdrcharset = pax_headers.get("hdrcharset")
  1062. if hdrcharset == "BINARY":
  1063. encoding = tarfile.encoding
  1064. else:
  1065. encoding = "utf-8"
  1066. # Parse pax header information. A record looks like that:
  1067. # "%d %s=%s\n" % (length, keyword, value). length is the size
  1068. # of the complete record including the length field itself and
  1069. # the newline. keyword and value are both UTF-8 encoded strings.
  1070. regex = re.compile(br"(\d+) ([^=]+)=")
  1071. pos = 0
  1072. while True:
  1073. match = regex.match(buf, pos)
  1074. if not match:
  1075. break
  1076. length, keyword = match.groups()
  1077. length = int(length)
  1078. value = buf[match.end(2) + 1:match.start(1) + length - 1]
  1079. # Normally, we could just use "utf-8" as the encoding and "strict"
  1080. # as the error handler, but we better not take the risk. For
  1081. # example, GNU tar <= 1.23 is known to store filenames it cannot
  1082. # translate to UTF-8 as raw strings (unfortunately without a
  1083. # hdrcharset=BINARY header).
  1084. # We first try the strict standard encoding, and if that fails we
  1085. # fall back on the user's encoding and error handler.
  1086. keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
  1087. tarfile.errors)
  1088. if keyword in PAX_NAME_FIELDS:
  1089. value = self._decode_pax_field(value, encoding, tarfile.encoding,
  1090. tarfile.errors)
  1091. else:
  1092. value = self._decode_pax_field(value, "utf-8", "utf-8",
  1093. tarfile.errors)
  1094. pax_headers[keyword] = value
  1095. pos += length
  1096. # Fetch the next header.
  1097. try:
  1098. next = self.fromtarfile(tarfile)
  1099. except HeaderError:
  1100. raise SubsequentHeaderError("missing or bad subsequent header")
  1101. # Process GNU sparse information.
  1102. if "GNU.sparse.map" in pax_headers:
  1103. # GNU extended sparse format version 0.1.
  1104. self._proc_gnusparse_01(next, pax_headers)
  1105. elif "GNU.sparse.size" in pax_headers:
  1106. # GNU extended sparse format version 0.0.
  1107. self._proc_gnusparse_00(next, pax_headers, buf)
  1108. elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
  1109. # GNU extended sparse format version 1.0.
  1110. self._proc_gnusparse_10(next, pax_headers, tarfile)
  1111. if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
  1112. # Patch the TarInfo object with the extended header info.
  1113. next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
  1114. next.offset = self.offset
  1115. if "size" in pax_headers:
  1116. # If the extended header replaces the size field,
  1117. # we need to recalculate the offset where the next
  1118. # header starts.
  1119. offset = next.offset_data
  1120. if next.isreg() or next.type not in SUPPORTED_TYPES:
  1121. offset += next._block(next.size)
  1122. tarfile.offset = offset
  1123. return next
  1124. def _proc_gnusparse_00(self, next, pax_headers, buf):
  1125. """Process a GNU tar extended sparse header, version 0.0.
  1126. """
  1127. offsets = []
  1128. for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
  1129. offsets.append(int(match.group(1)))
  1130. numbytes = []
  1131. for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
  1132. numbytes.append(int(match.group(1)))
  1133. next.sparse = list(zip(offsets, numbytes))
  1134. def _proc_gnusparse_01(self, next, pax_headers):
  1135. """Process a GNU tar extended sparse header, version 0.1.
  1136. """
  1137. sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")]
  1138. next.sparse = list(zip(sparse[::2], sparse[1::2]))
  1139. def _proc_gnusparse_10(self, next, pax_headers, tarfile):
  1140. """Process a GNU tar extended sparse header, version 1.0.
  1141. """
  1142. fields = None
  1143. sparse = []
  1144. buf = tarfile.fileobj.read(BLOCKSIZE)
  1145. fields, buf = buf.split(b"\n", 1)
  1146. fields = int(fields)
  1147. while len(sparse) < fields * 2:
  1148. if b"\n" not in buf:
  1149. buf += tarfile.fileobj.read(BLOCKSIZE)
  1150. number, buf = buf.split(b"\n", 1)
  1151. sparse.append(int(number))
  1152. next.offset_data = tarfile.fileobj.tell()
  1153. next.sparse = list(zip(sparse[::2], sparse[1::2]))
  1154. def _apply_pax_info(self, pax_headers, encoding, errors):
  1155. """Replace fields with supplemental information from a previous
  1156. pax extended or global header.
  1157. """
  1158. for keyword, value in pax_headers.items():
  1159. if keyword == "GNU.sparse.name":
  1160. setattr(self, "path", value)
  1161. elif keyword == "GNU.sparse.size":
  1162. setattr(self, "size", int(value))
  1163. elif keyword == "GNU.sparse.realsize":
  1164. setattr(self, "size", int(value))
  1165. elif keyword in PAX_FIELDS:
  1166. if keyword in PAX_NUMBER_FIELDS:
  1167. try:
  1168. value = PAX_NUMBER_FIELDS[keyword](value)
  1169. except ValueError:
  1170. value = 0
  1171. if keyword == "path":
  1172. value = value.rstrip("/")
  1173. setattr(self, keyword, value)
  1174. self.pax_headers = pax_headers.copy()
  1175. def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
  1176. """Decode a single field from a pax record.
  1177. """
  1178. try:
  1179. return value.decode(encoding, "strict")
  1180. except UnicodeDecodeError:
  1181. return value.decode(fallback_encoding, fallback_errors)
  1182. def _block(self, count):
  1183. """Round up a byte count by BLOCKSIZE and return it,
  1184. e.g. _block(834) => 1024.
  1185. """
  1186. blocks, remainder = divmod(count, BLOCKSIZE)
  1187. if remainder:
  1188. blocks += 1
  1189. return blocks * BLOCKSIZE
  1190. def isreg(self):
  1191. return self.type in REGULAR_TYPES
  1192. def isfile(self):
  1193. return self.isreg()
  1194. def isdir(self):
  1195. return self.type == DIRTYPE
  1196. def issym(self):
  1197. return self.type == SYMTYPE
  1198. def islnk(self):
  1199. return self.type == LNKTYPE
  1200. def ischr(self):
  1201. return self.type == CHRTYPE
  1202. def isblk(self):
  1203. return self.type == BLKTYPE
  1204. def isfifo(self):
  1205. return self.type == FIFOTYPE
  1206. def issparse(self):
  1207. return self.sparse is not None
  1208. def isdev(self):
  1209. return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
  1210. # class TarInfo
  1211. class TarFile(object):
  1212. """The TarFile Class provides an interface to tar archives.
  1213. """
  1214. debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
  1215. dereference = False # If true, add content of linked file to the
  1216. # tar file, else the link.
  1217. ignore_zeros = False # If true, skips empty or invalid blocks and
  1218. # continues processing.
  1219. errorlevel = 1 # If 0, fatal errors only appear in debug
  1220. # messages (if debug >= 0). If > 0, errors
  1221. # are passed to the caller as exceptions.
  1222. format = DEFAULT_FORMAT # The format to use when creating an archive.
  1223. encoding = ENCODING # Encoding for 8-bit character strings.
  1224. errors = None # Error handler for unicode conversion.
  1225. tarinfo = TarInfo # The default TarInfo class to use.
  1226. fileobject = ExFileObject # The file-object for extractfile().
  1227. def __init__(self, name=None, mode="r", fileobj=None, format=None,
  1228. tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
  1229. errors="surrogateescape", pax_headers=None, debug=None,
  1230. errorlevel=None, copybufsize=None):
  1231. """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
  1232. read from an existing archive, 'a' to append data to an existing
  1233. file or 'w' to create a new file overwriting an existing one. `mode'
  1234. defaults to 'r'.
  1235. If `fileobj' is given, it is used for reading or writing data. If it
  1236. can be determined, `mode' is overridden by `fileobj's mode.
  1237. `fileobj' is not closed, when TarFile is closed.
  1238. """
  1239. modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
  1240. if mode not in modes:
  1241. raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
  1242. self.mode = mode
  1243. self._mode = modes[mode]
  1244. if not fileobj:
  1245. if self.mode == "a" and not os.path.exists(name):
  1246. # Create nonexistent files in append mode.
  1247. self.mode = "w"
  1248. self._mode = "wb"
  1249. fileobj = bltn_open(name, self._mode)
  1250. self._extfileobj = False
  1251. else:
  1252. if (name is None and hasattr(fileobj, "name") and
  1253. isinstance(fileobj.name, (str, bytes))):
  1254. name = fileobj.name
  1255. if hasattr(fileobj, "mode"):
  1256. self._mode = fileobj.mode
  1257. self._extfileobj = True
  1258. self.name = os.path.abspath(name) if name else None
  1259. self.fileobj = fileobj
  1260. # Init attributes.
  1261. if format is not None:
  1262. self.format = format
  1263. if tarinfo is not None:
  1264. self.tarinfo = tarinfo
  1265. if dereference is not None:
  1266. self.dereference = dereference
  1267. if ignore_zeros is not None:
  1268. self.ignore_zeros = ignore_zeros
  1269. if encoding is not None:
  1270. self.encoding = encoding
  1271. self.errors = errors
  1272. if pax_headers is not None and self.format == PAX_FORMAT:
  1273. self.pax_headers = pax_headers
  1274. else:
  1275. self.pax_headers = {}
  1276. if debug is not None:
  1277. self.debug = debug
  1278. if errorlevel is not None:
  1279. self.errorlevel = errorlevel
  1280. # Init datastructures.
  1281. self.copybufsize = copybufsize
  1282. self.closed = False
  1283. self.members = [] # list of members as TarInfo objects
  1284. self._loaded = False # flag if all members have been read
  1285. self.offset = self.fileobj.tell()
  1286. # current position in the archive file
  1287. self.inodes = {} # dictionary caching the inodes of
  1288. # archive members already added
  1289. try:
  1290. if self.mode == "r":
  1291. self.firstmember = None
  1292. self.firstmember = self.next()
  1293. if self.mode == "a":
  1294. # Move to the end of the archive,
  1295. # before the first empty block.
  1296. while True:
  1297. self.fileobj.seek(self.offset)
  1298. try:
  1299. tarinfo = self.tarinfo.fromtarfile(self)
  1300. self.members.append(tarinfo)
  1301. except EOFHeaderError:
  1302. self.fileobj.seek(self.offset)
  1303. break
  1304. except HeaderError as e:
  1305. raise ReadError(str(e))
  1306. if self.mode in ("a", "w", "x"):
  1307. self._loaded = True
  1308. if self.pax_headers:
  1309. buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
  1310. self.fileobj.write(buf)
  1311. self.offset += len(buf)
  1312. except:
  1313. if not self._extfileobj:
  1314. self.fileobj.close()
  1315. self.closed = True
  1316. raise
  1317. #--------------------------------------------------------------------------
  1318. # Below are the classmethods which act as alternate constructors to the
  1319. # TarFile class. The open() method is the only one that is needed for
  1320. # public use; it is the "super"-constructor and is able to select an
  1321. # adequate "sub"-constructor for a particular compression using the mapping
  1322. # from OPEN_METH.
  1323. #
  1324. # This concept allows one to subclass TarFile without losing the comfort of
  1325. # the super-constructor. A sub-constructor is registered and made available
  1326. # by adding it to the mapping in OPEN_METH.
  1327. @classmethod
  1328. def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
  1329. """Open a tar archive for reading, writing or appending. Return
  1330. an appropriate TarFile class.
  1331. mode:
  1332. 'r' or 'r:*' open for reading with transparent compression
  1333. 'r:' open for reading exclusively uncompressed
  1334. 'r:gz' open for reading with gzip compression
  1335. 'r:bz2' open for reading with bzip2 compression
  1336. 'r:xz' open for reading with lzma compression
  1337. 'a' or 'a:' open for appending, creating the file if necessary
  1338. 'w' or 'w:' open for writing without compression
  1339. 'w:gz' open for writing with gzip compression
  1340. 'w:bz2' open for writing with bzip2 compression
  1341. 'w:xz' open for writing with lzma compression
  1342. 'x' or 'x:' create a tarfile exclusively without compression, raise
  1343. an exception if the file is already created
  1344. 'x:gz' create a gzip compressed tarfile, raise an exception
  1345. if the file is already created
  1346. 'x:bz2' create a bzip2 compressed tarfile, raise an exception
  1347. if the file is already created
  1348. 'x:xz' create an lzma compressed tarfile, raise an exception
  1349. if the file is already created
  1350. 'r|*' open a stream of tar blocks with transparent compression
  1351. 'r|' open an uncompressed stream of tar blocks for reading
  1352. 'r|gz' open a gzip compressed stream of tar blocks
  1353. 'r|bz2' open a bzip2 compressed stream of tar blocks
  1354. 'r|xz' open an lzma compressed stream of tar blocks
  1355. 'w|' open an uncompressed stream for writing
  1356. 'w|gz' open a gzip compressed stream for writing
  1357. 'w|bz2' open a bzip2 compressed stream for writing
  1358. 'w|xz' open an lzma compressed stream for writing
  1359. """
  1360. if not name and not fileobj:
  1361. raise ValueError("nothing to open")
  1362. if mode in ("r", "r:*"):
  1363. # Find out which *open() is appropriate for opening the file.
  1364. def not_compressed(comptype):
  1365. return cls.OPEN_METH[comptype] == 'taropen'
  1366. for comptype in sorted(cls.OPEN_METH, key=not_compressed):
  1367. func = getattr(cls, cls.OPEN_METH[comptype])
  1368. if fileobj is not None:
  1369. saved_pos = fileobj.tell()
  1370. try:
  1371. return func(name, "r", fileobj, **kwargs)
  1372. except (ReadError, CompressionError):
  1373. if fileobj is not None:
  1374. fileobj.seek(saved_pos)
  1375. continue
  1376. raise ReadError("file could not be opened successfully")
  1377. elif ":" in mode:
  1378. filemode, comptype = mode.split(":", 1)
  1379. filemode = filemode or "r"
  1380. comptype = comptype or "tar"
  1381. # Select the *open() function according to
  1382. # given compression.
  1383. if comptype in cls.OPEN_METH:
  1384. func = getattr(cls, cls.OPEN_METH[comptype])
  1385. else:
  1386. raise CompressionError("unknown compression type %r" % comptype)
  1387. return func(name, filemode, fileobj, **kwargs)
  1388. elif "|" in mode:
  1389. filemode, comptype = mode.split("|", 1)
  1390. filemode = filemode or "r"
  1391. comptype = comptype or "tar"
  1392. if filemode not in ("r", "w"):
  1393. raise ValueError("mode must be 'r' or 'w'")
  1394. stream = _Stream(name, filemode, comptype, fileobj, bufsize)
  1395. try:
  1396. t = cls(name, filemode, stream, **kwargs)
  1397. except:
  1398. stream.close()
  1399. raise
  1400. t._extfileobj = False
  1401. return t
  1402. elif mode in ("a", "w", "x"):
  1403. return cls.taropen(name, mode, fileobj, **kwargs)
  1404. raise ValueError("undiscernible mode")
  1405. @classmethod
  1406. def taropen(cls, name, mode="r", fileobj=None, **kwargs):
  1407. """Open uncompressed tar archive name for reading or writing.
  1408. """
  1409. if mode not in ("r", "a", "w", "x"):
  1410. raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
  1411. return cls(name, mode, fileobj, **kwargs)
  1412. @classmethod
  1413. def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
  1414. """Open gzip compressed tar archive name for reading or writing.
  1415. Appending is not allowed.
  1416. """
  1417. if mode not in ("r", "w", "x"):
  1418. raise ValueError("mode must be 'r', 'w' or 'x'")
  1419. try:
  1420. import gzip
  1421. gzip.GzipFile
  1422. except (ImportError, AttributeError):
  1423. raise CompressionError("gzip module is not available")
  1424. try:
  1425. fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj)
  1426. except OSError:
  1427. if fileobj is not None and mode == 'r':
  1428. raise ReadError("not a gzip file")
  1429. raise
  1430. try:
  1431. t = cls.taropen(name, mode, fileobj, **kwargs)
  1432. except OSError:
  1433. fileobj.close()
  1434. if mode == 'r':
  1435. raise ReadError("not a gzip file")
  1436. raise
  1437. except:
  1438. fileobj.close()
  1439. raise
  1440. t._extfileobj = False
  1441. return t
  1442. @classmethod
  1443. def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
  1444. """Open bzip2 compressed tar archive name for reading or writing.
  1445. Appending is not allowed.
  1446. """
  1447. if mode not in ("r", "w", "x"):
  1448. raise ValueError("mode must be 'r', 'w' or 'x'")
  1449. try:
  1450. import bz2
  1451. except ImportError:
  1452. raise CompressionError("bz2 module is not available")
  1453. fileobj = bz2.BZ2File(fileobj or name, mode,
  1454. compresslevel=compresslevel)
  1455. try:
  1456. t = cls.taropen(name, mode, fileobj, **kwargs)
  1457. except (OSError, EOFError):
  1458. fileobj.close()
  1459. if mode == 'r':
  1460. raise ReadError("not a bzip2 file")
  1461. raise
  1462. except:
  1463. fileobj.close()
  1464. raise
  1465. t._extfileobj = False
  1466. return t
  1467. @classmethod
  1468. def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
  1469. """Open lzma compressed tar archive name for reading or writing.
  1470. Appending is not allowed.
  1471. """
  1472. if mode not in ("r", "w", "x"):
  1473. raise ValueError("mode must be 'r', 'w' or 'x'")
  1474. try:
  1475. import lzma
  1476. except ImportError:
  1477. raise CompressionError("lzma module is not available")
  1478. fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset)
  1479. try:
  1480. t = cls.taropen(name, mode, fileobj, **kwargs)
  1481. except (lzma.LZMAError, EOFError):
  1482. fileobj.close()
  1483. if mode == 'r':
  1484. raise ReadError("not an lzma file")
  1485. raise
  1486. except:
  1487. fileobj.close()
  1488. raise
  1489. t._extfileobj = False
  1490. return t
  1491. # All *open() methods are registered here.
  1492. OPEN_METH = {
  1493. "tar": "taropen", # uncompressed tar
  1494. "gz": "gzopen", # gzip compressed tar
  1495. "bz2": "bz2open", # bzip2 compressed tar
  1496. "xz": "xzopen" # lzma compressed tar
  1497. }
  1498. #--------------------------------------------------------------------------
  1499. # The public methods which TarFile provides:
  1500. def close(self):
  1501. """Close the TarFile. In write-mode, two finishing zero blocks are
  1502. appended to the archive.
  1503. """
  1504. if self.closed:
  1505. return
  1506. self.closed = True
  1507. try:
  1508. if self.mode in ("a", "w", "x"):
  1509. self.fileobj.write(NUL * (BLOCKSIZE * 2))
  1510. self.offset += (BLOCKSIZE * 2)
  1511. # fill up the end with zero-blocks
  1512. # (like option -b20 for tar does)
  1513. blocks, remainder = divmod(self.offset, RECORDSIZE)
  1514. if remainder > 0:
  1515. self.fileobj.write(NUL * (RECORDSIZE - remainder))
  1516. finally:
  1517. if not self._extfileobj:
  1518. self.fileobj.close()
  1519. def getmember(self, name):
  1520. """Return a TarInfo object for member `name'. If `name' can not be
  1521. found in the archive, KeyError is raised. If a member occurs more
  1522. than once in the archive, its last occurrence is assumed to be the
  1523. most up-to-date version.
  1524. """
  1525. tarinfo = self._getmember(name)
  1526. if tarinfo is None:
  1527. raise KeyError("filename %r not found" % name)
  1528. return tarinfo
  1529. def getmembers(self):
  1530. """Return the members of the archive as a list of TarInfo objects. The
  1531. list has the same order as the members in the archive.
  1532. """
  1533. self._check()
  1534. if not self._loaded: # if we want to obtain a list of
  1535. self._load() # all members, we first have to
  1536. # scan the whole archive.
  1537. return self.members
  1538. def getnames(self):
  1539. """Return the members of the archive as a list of their names. It has
  1540. the same order as the list returned by getmembers().
  1541. """
  1542. return [tarinfo.name for tarinfo in self.getmembers()]
  1543. def gettarinfo(self, name=None, arcname=None, fileobj=None):
  1544. """Create a TarInfo object from the result of os.stat or equivalent
  1545. on an existing file. The file is either named by `name', or
  1546. specified as a file object `fileobj' with a file descriptor. If
  1547. given, `arcname' specifies an alternative name for the file in the
  1548. archive, otherwise, the name is taken from the 'name' attribute of
  1549. 'fileobj', or the 'name' argument. The name should be a text
  1550. string.
  1551. """
  1552. self._check("awx")
  1553. # When fileobj is given, replace name by
  1554. # fileobj's real name.
  1555. if fileobj is not None:
  1556. name = fileobj.name
  1557. # Building the name of the member in the archive.
  1558. # Backward slashes are converted to forward slashes,
  1559. # Absolute paths are turned to relative paths.
  1560. if arcname is None:
  1561. arcname = name
  1562. drv, arcname = os.path.splitdrive(arcname)
  1563. arcname = arcname.replace(os.sep, "/")
  1564. arcname = arcname.lstrip("/")
  1565. # Now, fill the TarInfo object with
  1566. # information specific for the file.
  1567. tarinfo = self.tarinfo()
  1568. tarinfo.tarfile = self # Not needed
  1569. # Use os.stat or os.lstat, depending on platform
  1570. # and if symlinks shall be resolved.
  1571. if fileobj is None:
  1572. if hasattr(os, "lstat") and not self.dereference:
  1573. statres = os.lstat(name)
  1574. else:
  1575. statres = os.stat(name)
  1576. else:
  1577. statres = os.fstat(fileobj.fileno())
  1578. linkname = ""
  1579. stmd = statres.st_mode
  1580. if stat.S_ISREG(stmd):
  1581. inode = (statres.st_ino, statres.st_dev)
  1582. if not self.dereference and statres.st_nlink > 1 and \
  1583. inode in self.inodes and arcname != self.inodes[inode]:
  1584. # Is it a hardlink to an already
  1585. # archived file?
  1586. type = LNKTYPE
  1587. linkname = self.inodes[inode]
  1588. else:
  1589. # The inode is added only if its valid.
  1590. # For win32 it is always 0.
  1591. type = REGTYPE
  1592. if inode[0]:
  1593. self.inodes[inode] = arcname
  1594. elif stat.S_ISDIR(stmd):
  1595. type = DIRTYPE
  1596. elif stat.S_ISFIFO(stmd):
  1597. type = FIFOTYPE
  1598. elif stat.S_ISLNK(stmd):
  1599. type = SYMTYPE
  1600. linkname = os.readlink(name)
  1601. elif stat.S_ISCHR(stmd):
  1602. type = CHRTYPE
  1603. elif stat.S_ISBLK(stmd):
  1604. type = BLKTYPE
  1605. else:
  1606. return None
  1607. # Fill the TarInfo object with all
  1608. # information we can get.
  1609. tarinfo.name = arcname
  1610. tarinfo.mode = stmd
  1611. tarinfo.uid = statres.st_uid
  1612. tarinfo.gid = statres.st_gid
  1613. if type == REGTYPE:
  1614. tarinfo.size = statres.st_size
  1615. else:
  1616. tarinfo.size = 0
  1617. tarinfo.mtime = statres.st_mtime
  1618. tarinfo.type = type
  1619. tarinfo.linkname = linkname
  1620. if pwd:
  1621. try:
  1622. tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
  1623. except KeyError:
  1624. pass
  1625. if grp:
  1626. try:
  1627. tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
  1628. except KeyError:
  1629. pass
  1630. if type in (CHRTYPE, BLKTYPE):
  1631. if hasattr(os, "major") and hasattr(os, "minor"):
  1632. tarinfo.devmajor = os.major(statres.st_rdev)
  1633. tarinfo.devminor = os.minor(statres.st_rdev)
  1634. return tarinfo
  1635. def list(self, verbose=True, *, members=None):
  1636. """Print a table of contents to sys.stdout. If `verbose' is False, only
  1637. the names of the members are printed. If it is True, an `ls -l'-like
  1638. output is produced. `members' is optional and must be a subset of the
  1639. list returned by getmembers().
  1640. """
  1641. self._check()
  1642. if members is None:
  1643. members = self
  1644. for tarinfo in members:
  1645. if verbose:
  1646. _safe_print(stat.filemode(tarinfo.mode))
  1647. _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
  1648. tarinfo.gname or tarinfo.gid))
  1649. if tarinfo.ischr() or tarinfo.isblk():
  1650. _safe_print("%10s" %
  1651. ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
  1652. else:
  1653. _safe_print("%10d" % tarinfo.size)
  1654. _safe_print("%d-%02d-%02d %02d:%02d:%02d" \
  1655. % time.localtime(tarinfo.mtime)[:6])
  1656. _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
  1657. if verbose:
  1658. if tarinfo.issym():
  1659. _safe_print("-> " + tarinfo.linkname)
  1660. if tarinfo.islnk():
  1661. _safe_print("link to " + tarinfo.linkname)
  1662. print()
  1663. def add(self, name, arcname=None, recursive=True, *, filter=None):
  1664. """Add the file `name' to the archive. `name' may be any type of file
  1665. (directory, fifo, symbolic link, etc.). If given, `arcname'
  1666. specifies an alternative name for the file in the archive.
  1667. Directories are added recursively by default. This can be avoided by
  1668. setting `recursive' to False. `filter' is a function
  1669. that expects a TarInfo object argument and returns the changed
  1670. TarInfo object, if it returns None the TarInfo object will be
  1671. excluded from the archive.
  1672. """
  1673. self._check("awx")
  1674. if arcname is None:
  1675. arcname = name
  1676. # Skip if somebody tries to archive the archive...
  1677. if self.name is not None and os.path.abspath(name) == self.name:
  1678. self._dbg(2, "tarfile: Skipped %r" % name)
  1679. return
  1680. self._dbg(1, name)
  1681. # Create a TarInfo object from the file.
  1682. tarinfo = self.gettarinfo(name, arcname)
  1683. if tarinfo is None:
  1684. self._dbg(1, "tarfile: Unsupported type %r" % name)
  1685. return
  1686. # Change or exclude the TarInfo object.
  1687. if filter is not None:
  1688. tarinfo = filter(tarinfo)
  1689. if tarinfo is None:
  1690. self._dbg(2, "tarfile: Excluded %r" % name)
  1691. return
  1692. # Append the tar header and data to the archive.
  1693. if tarinfo.isreg():
  1694. with bltn_open(name, "rb") as f:
  1695. self.addfile(tarinfo, f)
  1696. elif tarinfo.isdir():
  1697. self.addfile(tarinfo)
  1698. if recursive:
  1699. for f in sorted(os.listdir(name)):
  1700. self.add(os.path.join(name, f), os.path.join(arcname, f),
  1701. recursive, filter=filter)
  1702. else:
  1703. self.addfile(tarinfo)
  1704. def addfile(self, tarinfo, fileobj=None):
  1705. """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
  1706. given, it should be a binary file, and tarinfo.size bytes are read
  1707. from it and added to the archive. You can create TarInfo objects
  1708. directly, or by using gettarinfo().
  1709. """
  1710. self._check("awx")
  1711. tarinfo = copy.copy(tarinfo)
  1712. buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
  1713. self.fileobj.write(buf)
  1714. self.offset += len(buf)
  1715. bufsize=self.copybufsize
  1716. # If there's data to follow, append it.
  1717. if fileobj is not None:
  1718. copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize)
  1719. blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
  1720. if remainder > 0:
  1721. self.fileobj.write(NUL * (BLOCKSIZE - remainder))
  1722. blocks += 1
  1723. self.offset += blocks * BLOCKSIZE
  1724. self.members.append(tarinfo)
  1725. def extractall(self, path=".", members=None, *, numeric_owner=False):
  1726. """Extract all members from the archive to the current working
  1727. directory and set owner, modification time and permissions on
  1728. directories afterwards. `path' specifies a different directory
  1729. to extract to. `members' is optional and must be a subset of the
  1730. list returned by getmembers(). If `numeric_owner` is True, only
  1731. the numbers for user/group names are used and not the names.
  1732. """
  1733. directories = []
  1734. if members is None:
  1735. members = self
  1736. for tarinfo in members:
  1737. if tarinfo.isdir():
  1738. # Extract directories with a safe mode.
  1739. directories.append(tarinfo)
  1740. tarinfo = copy.copy(tarinfo)
  1741. tarinfo.mode = 0o700
  1742. # Do not set_attrs directories, as we will do that further down
  1743. self.extract(tarinfo, path, set_attrs=not tarinfo.isdir(),
  1744. numeric_owner=numeric_owner)
  1745. # Reverse sort directories.
  1746. directories.sort(key=lambda a: a.name)
  1747. directories.reverse()
  1748. # Set correct owner, mtime and filemode on directories.
  1749. for tarinfo in directories:
  1750. dirpath = os.path.join(path, tarinfo.name)
  1751. try:
  1752. self.chown(tarinfo, dirpath, numeric_owner=numeric_owner)
  1753. self.utime(tarinfo, dirpath)
  1754. self.chmod(tarinfo, dirpath)
  1755. except ExtractError as e:
  1756. if self.errorlevel > 1:
  1757. raise
  1758. else:
  1759. self._dbg(1, "tarfile: %s" % e)
  1760. def extract(self, member, path="", set_attrs=True, *, numeric_owner=False):
  1761. """Extract a member from the archive to the current working directory,
  1762. using its full name. Its file information is extracted as accurately
  1763. as possible. `member' may be a filename or a TarInfo object. You can
  1764. specify a different directory using `path'. File attributes (owner,
  1765. mtime, mode) are set unless `set_attrs' is False. If `numeric_owner`
  1766. is True, only the numbers for user/group names are used and not
  1767. the names.
  1768. """
  1769. self._check("r")
  1770. if isinstance(member, str):
  1771. tarinfo = self.getmember(member)
  1772. else:
  1773. tarinfo = member
  1774. # Prepare the link target for makelink().
  1775. if tarinfo.islnk():
  1776. tarinfo._link_target = os.path.join(path, tarinfo.linkname)
  1777. try:
  1778. self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
  1779. set_attrs=set_attrs,
  1780. numeric_owner=numeric_owner)
  1781. except OSError as e:
  1782. if self.errorlevel > 0:
  1783. raise
  1784. else:
  1785. if e.filename is None:
  1786. self._dbg(1, "tarfile: %s" % e.strerror)
  1787. else:
  1788. self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
  1789. except ExtractError as e:
  1790. if self.errorlevel > 1:
  1791. raise
  1792. else:
  1793. self._dbg(1, "tarfile: %s" % e)
  1794. def extractfile(self, member):
  1795. """Extract a member from the archive as a file object. `member' may be
  1796. a filename or a TarInfo object. If `member' is a regular file or a
  1797. link, an io.BufferedReader object is returned. Otherwise, None is
  1798. returned.
  1799. """
  1800. self._check("r")
  1801. if isinstance(member, str):
  1802. tarinfo = self.getmember(member)
  1803. else:
  1804. tarinfo = member
  1805. if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
  1806. # Members with unknown types are treated as regular files.
  1807. return self.fileobject(self, tarinfo)
  1808. elif tarinfo.islnk() or tarinfo.issym():
  1809. if isinstance(self.fileobj, _Stream):
  1810. # A small but ugly workaround for the case that someone tries
  1811. # to extract a (sym)link as a file-object from a non-seekable
  1812. # stream of tar blocks.
  1813. raise StreamError("cannot extract (sym)link as file object")
  1814. else:
  1815. # A (sym)link's file object is its target's file object.
  1816. return self.extractfile(self._find_link_target(tarinfo))
  1817. else:
  1818. # If there's no data associated with the member (directory, chrdev,
  1819. # blkdev, etc.), return None instead of a file object.
  1820. return None
  1821. def _extract_member(self, tarinfo, targetpath, set_attrs=True,
  1822. numeric_owner=False):
  1823. """Extract the TarInfo object tarinfo to a physical
  1824. file called targetpath.
  1825. """
  1826. # Fetch the TarInfo object for the given name
  1827. # and build the destination pathname, replacing
  1828. # forward slashes to platform specific separators.
  1829. targetpath = targetpath.rstrip("/")
  1830. targetpath = targetpath.replace("/", os.sep)
  1831. # Create all upper directories.
  1832. upperdirs = os.path.dirname(targetpath)
  1833. if upperdirs and not os.path.exists(upperdirs):
  1834. # Create directories that are not part of the archive with
  1835. # default permissions.
  1836. os.makedirs(upperdirs)
  1837. if tarinfo.islnk() or tarinfo.issym():
  1838. self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
  1839. else:
  1840. self._dbg(1, tarinfo.name)
  1841. if tarinfo.isreg():
  1842. self.makefile(tarinfo, targetpath)
  1843. elif tarinfo.isdir():
  1844. self.makedir(tarinfo, targetpath)
  1845. elif tarinfo.isfifo():
  1846. self.makefifo(tarinfo, targetpath)
  1847. elif tarinfo.ischr() or tarinfo.isblk():
  1848. self.makedev(tarinfo, targetpath)
  1849. elif tarinfo.islnk() or tarinfo.issym():
  1850. self.makelink(tarinfo, targetpath)
  1851. elif tarinfo.type not in SUPPORTED_TYPES:
  1852. self.makeunknown(tarinfo, targetpath)
  1853. else:
  1854. self.makefile(tarinfo, targetpath)
  1855. if set_attrs:
  1856. self.chown(tarinfo, targetpath, numeric_owner)
  1857. if not tarinfo.issym():
  1858. self.chmod(tarinfo, targetpath)
  1859. self.utime(tarinfo, targetpath)
  1860. #--------------------------------------------------------------------------
  1861. # Below are the different file methods. They are called via
  1862. # _extract_member() when extract() is called. They can be replaced in a
  1863. # subclass to implement other functionality.
  1864. def makedir(self, tarinfo, targetpath):
  1865. """Make a directory called targetpath.
  1866. """
  1867. try:
  1868. # Use a safe mode for the directory, the real mode is set
  1869. # later in _extract_member().
  1870. os.mkdir(targetpath, 0o700)
  1871. except FileExistsError:
  1872. pass
  1873. def makefile(self, tarinfo, targetpath):
  1874. """Make a file called targetpath.
  1875. """
  1876. source = self.fileobj
  1877. source.seek(tarinfo.offset_data)
  1878. bufsize = self.copybufsize
  1879. with bltn_open(targetpath, "wb") as target:
  1880. if tarinfo.sparse is not None:
  1881. for offset, size in tarinfo.sparse:
  1882. target.seek(offset)
  1883. copyfileobj(source, target, size, ReadError, bufsize)
  1884. target.seek(tarinfo.size)
  1885. target.truncate()
  1886. else:
  1887. copyfileobj(source, target, tarinfo.size, ReadError, bufsize)
  1888. def makeunknown(self, tarinfo, targetpath):
  1889. """Make a file from a TarInfo object with an unknown type
  1890. at targetpath.
  1891. """
  1892. self.makefile(tarinfo, targetpath)
  1893. self._dbg(1, "tarfile: Unknown file type %r, " \
  1894. "extracted as regular file." % tarinfo.type)
  1895. def makefifo(self, tarinfo, targetpath):
  1896. """Make a fifo called targetpath.
  1897. """
  1898. if hasattr(os, "mkfifo"):
  1899. os.mkfifo(targetpath)
  1900. else:
  1901. raise ExtractError("fifo not supported by system")
  1902. def makedev(self, tarinfo, targetpath):
  1903. """Make a character or block device called targetpath.
  1904. """
  1905. if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
  1906. raise ExtractError("special devices not supported by system")
  1907. mode = tarinfo.mode
  1908. if tarinfo.isblk():
  1909. mode |= stat.S_IFBLK
  1910. else:
  1911. mode |= stat.S_IFCHR
  1912. os.mknod(targetpath, mode,
  1913. os.makedev(tarinfo.devmajor, tarinfo.devminor))
  1914. def makelink(self, tarinfo, targetpath):
  1915. """Make a (symbolic) link called targetpath. If it cannot be created
  1916. (platform limitation), we try to make a copy of the referenced file
  1917. instead of a link.
  1918. """
  1919. try:
  1920. # For systems that support symbolic and hard links.
  1921. if tarinfo.issym():
  1922. os.symlink(tarinfo.linkname, targetpath)
  1923. else:
  1924. # See extract().
  1925. if os.path.exists(tarinfo._link_target):
  1926. os.link(tarinfo._link_target, targetpath)
  1927. else:
  1928. self._extract_member(self._find_link_target(tarinfo),
  1929. targetpath)
  1930. except symlink_exception:
  1931. try:
  1932. self._extract_member(self._find_link_target(tarinfo),
  1933. targetpath)
  1934. except KeyError:
  1935. raise ExtractError("unable to resolve link inside archive")
  1936. def chown(self, tarinfo, targetpath, numeric_owner):
  1937. """Set owner of targetpath according to tarinfo. If numeric_owner
  1938. is True, use .gid/.uid instead of .gname/.uname. If numeric_owner
  1939. is False, fall back to .gid/.uid when the search based on name
  1940. fails.
  1941. """
  1942. if hasattr(os, "geteuid") and os.geteuid() == 0:
  1943. # We have to be root to do so.
  1944. g = tarinfo.gid
  1945. u = tarinfo.uid
  1946. if not numeric_owner:
  1947. try:
  1948. if grp:
  1949. g = grp.getgrnam(tarinfo.gname)[2]
  1950. except KeyError:
  1951. pass
  1952. try:
  1953. if pwd:
  1954. u = pwd.getpwnam(tarinfo.uname)[2]
  1955. except KeyError:
  1956. pass
  1957. try:
  1958. if tarinfo.issym() and hasattr(os, "lchown"):
  1959. os.lchown(targetpath, u, g)
  1960. else:
  1961. os.chown(targetpath, u, g)
  1962. except OSError:
  1963. raise ExtractError("could not change owner")
  1964. def chmod(self, tarinfo, targetpath):
  1965. """Set file permissions of targetpath according to tarinfo.
  1966. """
  1967. if hasattr(os, 'chmod'):
  1968. try:
  1969. os.chmod(targetpath, tarinfo.mode)
  1970. except OSError:
  1971. raise ExtractError("could not change mode")
  1972. def utime(self, tarinfo, targetpath):
  1973. """Set modification time of targetpath according to tarinfo.
  1974. """
  1975. if not hasattr(os, 'utime'):
  1976. return
  1977. try:
  1978. os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
  1979. except OSError:
  1980. raise ExtractError("could not change modification time")
  1981. #--------------------------------------------------------------------------
  1982. def next(self):
  1983. """Return the next member of the archive as a TarInfo object, when
  1984. TarFile is opened for reading. Return None if there is no more
  1985. available.
  1986. """
  1987. self._check("ra")
  1988. if self.firstmember is not None:
  1989. m = self.firstmember
  1990. self.firstmember = None
  1991. return m
  1992. # Advance the file pointer.
  1993. if self.offset != self.fileobj.tell():
  1994. self.fileobj.seek(self.offset - 1)
  1995. if not self.fileobj.read(1):
  1996. raise ReadError("unexpected end of data")
  1997. # Read the next block.
  1998. tarinfo = None
  1999. while True:
  2000. try:
  2001. tarinfo = self.tarinfo.fromtarfile(self)
  2002. except EOFHeaderError as e:
  2003. if self.ignore_zeros:
  2004. self._dbg(2, "0x%X: %s" % (self.offset, e))
  2005. self.offset += BLOCKSIZE
  2006. continue
  2007. except InvalidHeaderError as e:
  2008. if self.ignore_zeros:
  2009. self._dbg(2, "0x%X: %s" % (self.offset, e))
  2010. self.offset += BLOCKSIZE
  2011. continue
  2012. elif self.offset == 0:
  2013. raise ReadError(str(e))
  2014. except EmptyHeaderError:
  2015. if self.offset == 0:
  2016. raise ReadError("empty file")
  2017. except TruncatedHeaderError as e:
  2018. if self.offset == 0:
  2019. raise ReadError(str(e))
  2020. except SubsequentHeaderError as e:
  2021. raise ReadError(str(e))
  2022. break
  2023. if tarinfo is not None:
  2024. self.members.append(tarinfo)
  2025. else:
  2026. self._loaded = True
  2027. return tarinfo
  2028. #--------------------------------------------------------------------------
  2029. # Little helper methods:
  2030. def _getmember(self, name, tarinfo=None, normalize=False):
  2031. """Find an archive member by name from bottom to top.
  2032. If tarinfo is given, it is used as the starting point.
  2033. """
  2034. # Ensure that all members have been loaded.
  2035. members = self.getmembers()
  2036. # Limit the member search list up to tarinfo.
  2037. if tarinfo is not None:
  2038. members = members[:members.index(tarinfo)]
  2039. if normalize:
  2040. name = os.path.normpath(name)
  2041. for member in reversed(members):
  2042. if normalize:
  2043. member_name = os.path.normpath(member.name)
  2044. else:
  2045. member_name = member.name
  2046. if name == member_name:
  2047. return member
  2048. def _load(self):
  2049. """Read through the entire archive file and look for readable
  2050. members.
  2051. """
  2052. while True:
  2053. tarinfo = self.next()
  2054. if tarinfo is None:
  2055. break
  2056. self._loaded = True
  2057. def _check(self, mode=None):
  2058. """Check if TarFile is still open, and if the operation's mode
  2059. corresponds to TarFile's mode.
  2060. """
  2061. if self.closed:
  2062. raise OSError("%s is closed" % self.__class__.__name__)
  2063. if mode is not None and self.mode not in mode:
  2064. raise OSError("bad operation for mode %r" % self.mode)
  2065. def _find_link_target(self, tarinfo):
  2066. """Find the target member of a symlink or hardlink member in the
  2067. archive.
  2068. """
  2069. if tarinfo.issym():
  2070. # Always search the entire archive.
  2071. linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
  2072. limit = None
  2073. else:
  2074. # Search the archive before the link, because a hard link is
  2075. # just a reference to an already archived file.
  2076. linkname = tarinfo.linkname
  2077. limit = tarinfo
  2078. member = self._getmember(linkname, tarinfo=limit, normalize=True)
  2079. if member is None:
  2080. raise KeyError("linkname %r not found" % linkname)
  2081. return member
  2082. def __iter__(self):
  2083. """Provide an iterator object.
  2084. """
  2085. if self._loaded:
  2086. yield from self.members
  2087. return
  2088. # Yield items using TarFile's next() method.
  2089. # When all members have been read, set TarFile as _loaded.
  2090. index = 0
  2091. # Fix for SF #1100429: Under rare circumstances it can
  2092. # happen that getmembers() is called during iteration,
  2093. # which will have already exhausted the next() method.
  2094. if self.firstmember is not None:
  2095. tarinfo = self.next()
  2096. index += 1
  2097. yield tarinfo
  2098. while True:
  2099. if index < len(self.members):
  2100. tarinfo = self.members[index]
  2101. elif not self._loaded:
  2102. tarinfo = self.next()
  2103. if not tarinfo:
  2104. self._loaded = True
  2105. return
  2106. else:
  2107. return
  2108. index += 1
  2109. yield tarinfo
  2110. def _dbg(self, level, msg):
  2111. """Write debugging output to sys.stderr.
  2112. """
  2113. if level <= self.debug:
  2114. print(msg, file=sys.stderr)
  2115. def __enter__(self):
  2116. self._check()
  2117. return self
  2118. def __exit__(self, type, value, traceback):
  2119. if type is None:
  2120. self.close()
  2121. else:
  2122. # An exception occurred. We must not call close() because
  2123. # it would try to write end-of-archive blocks and padding.
  2124. if not self._extfileobj:
  2125. self.fileobj.close()
  2126. self.closed = True
  2127. #--------------------
  2128. # exported functions
  2129. #--------------------
  2130. def is_tarfile(name):
  2131. """Return True if name points to a tar archive that we
  2132. are able to handle, else return False.
  2133. """
  2134. try:
  2135. t = open(name)
  2136. t.close()
  2137. return True
  2138. except TarError:
  2139. return False
  2140. open = TarFile.open
  2141. def main():
  2142. import argparse
  2143. description = 'A simple command-line interface for tarfile module.'
  2144. parser = argparse.ArgumentParser(description=description)
  2145. parser.add_argument('-v', '--verbose', action='store_true', default=False,
  2146. help='Verbose output')
  2147. group = parser.add_mutually_exclusive_group(required=True)
  2148. group.add_argument('-l', '--list', metavar='<tarfile>',
  2149. help='Show listing of a tarfile')
  2150. group.add_argument('-e', '--extract', nargs='+',
  2151. metavar=('<tarfile>', '<output_dir>'),
  2152. help='Extract tarfile into target dir')
  2153. group.add_argument('-c', '--create', nargs='+',
  2154. metavar=('<name>', '<file>'),
  2155. help='Create tarfile from sources')
  2156. group.add_argument('-t', '--test', metavar='<tarfile>',
  2157. help='Test if a tarfile is valid')
  2158. args = parser.parse_args()
  2159. if args.test is not None:
  2160. src = args.test
  2161. if is_tarfile(src):
  2162. with open(src, 'r') as tar:
  2163. tar.getmembers()
  2164. print(tar.getmembers(), file=sys.stderr)
  2165. if args.verbose:
  2166. print('{!r} is a tar archive.'.format(src))
  2167. else:
  2168. parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
  2169. elif args.list is not None:
  2170. src = args.list
  2171. if is_tarfile(src):
  2172. with TarFile.open(src, 'r:*') as tf:
  2173. tf.list(verbose=args.verbose)
  2174. else:
  2175. parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
  2176. elif args.extract is not None:
  2177. if len(args.extract) == 1:
  2178. src = args.extract[0]
  2179. curdir = os.curdir
  2180. elif len(args.extract) == 2:
  2181. src, curdir = args.extract
  2182. else:
  2183. parser.exit(1, parser.format_help())
  2184. if is_tarfile(src):
  2185. with TarFile.open(src, 'r:*') as tf:
  2186. tf.extractall(path=curdir)
  2187. if args.verbose:
  2188. if curdir == '.':
  2189. msg = '{!r} file is extracted.'.format(src)
  2190. else:
  2191. msg = ('{!r} file is extracted '
  2192. 'into {!r} directory.').format(src, curdir)
  2193. print(msg)
  2194. else:
  2195. parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
  2196. elif args.create is not None:
  2197. tar_name = args.create.pop(0)
  2198. _, ext = os.path.splitext(tar_name)
  2199. compressions = {
  2200. # gz
  2201. '.gz': 'gz',
  2202. '.tgz': 'gz',
  2203. # xz
  2204. '.xz': 'xz',
  2205. '.txz': 'xz',
  2206. # bz2
  2207. '.bz2': 'bz2',
  2208. '.tbz': 'bz2',
  2209. '.tbz2': 'bz2',
  2210. '.tb2': 'bz2',
  2211. }
  2212. tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w'
  2213. tar_files = args.create
  2214. with TarFile.open(tar_name, tar_mode) as tf:
  2215. for file_name in tar_files:
  2216. tf.add(file_name)
  2217. if args.verbose:
  2218. print('{!r} file created.'.format(tar_name))
  2219. if __name__ == '__main__':
  2220. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...