1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.compress.archivers.tar;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.UncheckedIOException;
24 import java.math.BigDecimal;
25 import java.nio.file.DirectoryStream;
26 import java.nio.file.Files;
27 import java.nio.file.LinkOption;
28 import java.nio.file.Path;
29 import java.nio.file.attribute.BasicFileAttributes;
30 import java.nio.file.attribute.DosFileAttributes;
31 import java.nio.file.attribute.FileTime;
32 import java.nio.file.attribute.PosixFileAttributes;
33 import java.time.DateTimeException;
34 import java.time.Instant;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Objects;
43 import java.util.Set;
44 import java.util.regex.Pattern;
45 import java.util.stream.Collectors;
46
47 import org.apache.commons.compress.archivers.ArchiveEntry;
48 import org.apache.commons.compress.archivers.EntryStreamOffsets;
49 import org.apache.commons.compress.archivers.zip.ZipEncoding;
50 import org.apache.commons.compress.utils.ArchiveUtils;
51 import org.apache.commons.compress.utils.IOUtils;
52 import org.apache.commons.compress.utils.ParsingUtils;
53 import org.apache.commons.io.file.attribute.FileTimes;
54 import org.apache.commons.lang3.StringUtils;
55 import org.apache.commons.lang3.SystemProperties;
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 public class TarArchiveEntry implements ArchiveEntry, TarConstants, EntryStreamOffsets {
185
186 private static final TarArchiveEntry[] EMPTY_TAR_ARCHIVE_ENTRY_ARRAY = {};
187
188
189
190
191
192
193
194 public static final long UNKNOWN = -1L;
195
196
197 public static final int MAX_NAMELEN = 31;
198
199
200 public static final int DEFAULT_DIR_MODE = 040755;
201
202
203 public static final int DEFAULT_FILE_MODE = 0100644;
204
205
206
207
208
209
210 @Deprecated
211 public static final int MILLIS_PER_SECOND = 1000;
212
213
214
215
216
217
218
219
220 private static final Pattern PAX_EXTENDED_HEADER_FILE_TIMES_PATTERN = Pattern.compile("-?\\d{1,19}(?:\\.\\d{1,19})?");
221
222 private static FileTime fileTimeFromOptionalSeconds(final long seconds) {
223 return seconds <= 0 ? null : FileTimes.fromUnixTime(seconds);
224 }
225
226
227
228
229 private static String normalizeFileName(String fileName, final boolean preserveAbsolutePath) {
230 if (!preserveAbsolutePath) {
231 final String property = SystemProperties.getOsName();
232 if (property != null) {
233 final String osName = StringUtils.toRootLowerCase(property);
234
235
236
237
238 if (osName.startsWith("windows")) {
239 if (fileName.length() > 2) {
240 final char ch1 = fileName.charAt(0);
241 final char ch2 = fileName.charAt(1);
242
243 if (ch2 == ':' && (ch1 >= 'a' && ch1 <= 'z' || ch1 >= 'A' && ch1 <= 'Z')) {
244 fileName = fileName.substring(2);
245 }
246 }
247 } else if (osName.contains("netware")) {
248 final int colon = fileName.indexOf(':');
249 if (colon != -1) {
250 fileName = fileName.substring(colon + 1);
251 }
252 }
253 }
254 }
255
256 fileName = fileName.replace(File.separatorChar, '/');
257
258
259
260
261 while (!preserveAbsolutePath && fileName.startsWith("/")) {
262 fileName = fileName.substring(1);
263 }
264 return fileName;
265 }
266
267 private static Instant parseInstantFromDecimalSeconds(final String value) throws IOException {
268
269 if (!PAX_EXTENDED_HEADER_FILE_TIMES_PATTERN.matcher(value).matches()) {
270 throw new IOException("Corrupted PAX header. Time field value is invalid '" + value + "'");
271 }
272
273 final BigDecimal epochSeconds = new BigDecimal(value);
274 final long seconds = epochSeconds.longValue();
275 final long nanos = epochSeconds.remainder(BigDecimal.ONE).movePointRight(9).longValue();
276 try {
277 return Instant.ofEpochSecond(seconds, nanos);
278 } catch (DateTimeException | ArithmeticException e) {
279
280
281 throw new IOException("Corrupted PAX header. Time field value is invalid '" + value + "'", e);
282 }
283 }
284
285
286 private String name = "";
287
288
289 private final boolean preserveAbsolutePath;
290
291
292 private int mode;
293
294
295 private long userId;
296
297
298 private long groupId;
299
300
301 private long size;
302
303
304
305
306 private FileTime mTime;
307
308
309
310
311
312
313 private FileTime cTime;
314
315
316
317
318
319
320 private FileTime aTime;
321
322
323
324
325
326
327 private FileTime birthTime;
328
329
330 private boolean checkSumOK;
331
332
333 private byte linkFlag;
334
335
336 private String linkName = "";
337
338
339 private String magic = MAGIC_POSIX;
340
341
342 private String version = VERSION_POSIX;
343
344
345 private String userName;
346
347
348 private String groupName = "";
349
350
351 private int devMajor;
352
353
354 private int devMinor;
355
356
357 private List<TarArchiveStructSparse> sparseHeaders;
358
359
360 private boolean isExtended;
361
362
363 private long realSize;
364
365
366 private boolean paxGNUSparse;
367
368
369
370
371 private boolean paxGNU1XSparse;
372
373
374 private boolean starSparse;
375
376
377 private final Path file;
378
379
380 private final LinkOption[] linkOptions;
381
382
383 private final Map<String, String> extraPaxHeaders = new HashMap<>();
384
385 private long dataOffset = OFFSET_UNKNOWN;
386
387
388
389
390 private TarArchiveEntry(final boolean preserveAbsolutePath) {
391 String user = SystemProperties.getUserName("");
392 if (user.length() > MAX_NAMELEN) {
393 user = user.substring(0, MAX_NAMELEN);
394 }
395 this.userName = user;
396 this.file = null;
397 this.linkOptions = IOUtils.EMPTY_LINK_OPTIONS;
398 this.preserveAbsolutePath = preserveAbsolutePath;
399 }
400
401
402
403
404
405
406
407 public TarArchiveEntry(final byte[] headerBuf) {
408 this(false);
409 parseTarHeader(headerBuf);
410 }
411
412
413
414
415
416
417
418
419
420
421 public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding) throws IOException {
422 this(headerBuf, encoding, false);
423 }
424
425
426
427
428
429
430
431
432
433
434
435
436 public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient) throws IOException {
437 this(Collections.emptyMap(), headerBuf, encoding, lenient);
438 }
439
440
441
442
443
444
445
446
447
448
449
450
451
452 public TarArchiveEntry(final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient, final long dataOffset) throws IOException {
453 this(headerBuf, encoding, lenient);
454 setDataOffset(dataOffset);
455 }
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471 public TarArchiveEntry(final File file) {
472 this(file, file.getPath());
473 }
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489 public TarArchiveEntry(final File file, final String fileName) {
490 final String normalizedName = normalizeFileName(fileName, false);
491 this.file = file.toPath();
492 this.linkOptions = IOUtils.EMPTY_LINK_OPTIONS;
493 try {
494 readFileMode(this.file, normalizedName);
495 } catch (final IOException e) {
496
497
498 if (!file.isDirectory()) {
499 this.size = file.length();
500 }
501 }
502 this.userName = "";
503 try {
504 readOsSpecificProperties(this.file);
505 } catch (final IOException e) {
506
507
508 this.mTime = FileTime.fromMillis(file.lastModified());
509 }
510 preserveAbsolutePath = false;
511 }
512
513
514
515
516
517
518
519
520
521
522
523
524
525 public TarArchiveEntry(final Map<String, String> globalPaxHeaders, final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient)
526 throws IOException {
527 this(false);
528 parseTarHeader(globalPaxHeaders, headerBuf, encoding, false, lenient);
529 }
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544 public TarArchiveEntry(final Map<String, String> globalPaxHeaders, final byte[] headerBuf, final ZipEncoding encoding, final boolean lenient,
545 final long dataOffset) throws IOException {
546 this(globalPaxHeaders, headerBuf, encoding, lenient);
547 setDataOffset(dataOffset);
548 }
549
550
551
552
553
554
555
556
557
558
559
560
561
562 public TarArchiveEntry(final Path file) throws IOException {
563 this(file, file.toString());
564 }
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579 public TarArchiveEntry(final Path file, final String fileName, final LinkOption... linkOptions) throws IOException {
580 final String normalizedName = normalizeFileName(fileName, false);
581 this.file = file;
582 this.linkOptions = linkOptions == null ? IOUtils.EMPTY_LINK_OPTIONS : linkOptions;
583 readFileMode(file, normalizedName, linkOptions);
584 this.userName = "";
585 readOsSpecificProperties(file);
586 preserveAbsolutePath = false;
587 }
588
589
590
591
592
593
594
595
596
597
598 public TarArchiveEntry(final String name) {
599 this(name, false);
600 }
601
602
603
604
605
606
607
608
609
610
611
612
613 public TarArchiveEntry(String name, final boolean preserveAbsolutePath) {
614 this(preserveAbsolutePath);
615 name = normalizeFileName(name, preserveAbsolutePath);
616 final boolean isDir = name.endsWith("/");
617 this.name = name;
618 this.mode = isDir ? DEFAULT_DIR_MODE : DEFAULT_FILE_MODE;
619 this.linkFlag = isDir ? LF_DIR : LF_NORMAL;
620 this.mTime = FileTime.from(Instant.now());
621 this.userName = "";
622 }
623
624
625
626
627
628
629
630
631
632
633
634 public TarArchiveEntry(final String name, final byte linkFlag) {
635 this(name, linkFlag, false);
636 }
637
638
639
640
641
642
643
644
645
646
647
648
649
650 public TarArchiveEntry(final String name, final byte linkFlag, final boolean preserveAbsolutePath) {
651 this(name, preserveAbsolutePath);
652 this.linkFlag = linkFlag;
653 if (linkFlag == LF_GNUTYPE_LONGNAME) {
654 magic = MAGIC_GNU;
655 version = VERSION_GNU_SPACE;
656 }
657 }
658
659
660
661
662
663
664
665
666
667 public void addPaxHeader(final String name, final String value) {
668 try {
669 processPaxHeader(name, value);
670 } catch (final IOException ex) {
671 throw new IllegalArgumentException("Invalid input", ex);
672 }
673 }
674
675
676
677
678
679
680 public void clearExtraPaxHeaders() {
681 extraPaxHeaders.clear();
682 }
683
684
685
686
687
688
689
690 @Override
691 public boolean equals(final Object it) {
692 if (it == null || getClass() != it.getClass()) {
693 return false;
694 }
695 return equals((TarArchiveEntry) it);
696 }
697
698
699
700
701
702
703
704 public boolean equals(final TarArchiveEntry it) {
705 return it != null && getName().equals(it.getName());
706 }
707
708
709
710
711
712
713
714 private int evaluateType(final Map<String, String> globalPaxHeaders, final byte[] header) {
715 if (ArchiveUtils.matchAsciiBuffer(MAGIC_GNU, header, MAGIC_OFFSET, MAGICLEN)) {
716 return FORMAT_OLDGNU;
717 }
718 if (ArchiveUtils.matchAsciiBuffer(MAGIC_POSIX, header, MAGIC_OFFSET, MAGICLEN)) {
719 if (isXstar(globalPaxHeaders, header)) {
720 return FORMAT_XSTAR;
721 }
722 return FORMAT_POSIX;
723 }
724 return 0;
725 }
726
727 private int fill(final byte value, final int offset, final byte[] outbuf, final int length) {
728 for (int i = 0; i < length; i++) {
729 outbuf[offset + i] = value;
730 }
731 return offset + length;
732 }
733
734 private int fill(final int value, final int offset, final byte[] outbuf, final int length) {
735 return fill((byte) value, offset, outbuf, length);
736 }
737
738 void fillGNUSparse0xData(final Map<String, String> headers) throws IOException {
739 paxGNUSparse = true;
740 realSize = ParsingUtils.parseIntValue(headers.get(TarGnuSparseKeys.SIZE));
741 if (headers.containsKey(TarGnuSparseKeys.NAME)) {
742
743 name = headers.get(TarGnuSparseKeys.NAME);
744 }
745 }
746
747 void fillGNUSparse1xData(final Map<String, String> headers) throws IOException {
748 paxGNUSparse = true;
749 paxGNU1XSparse = true;
750 if (headers.containsKey(TarGnuSparseKeys.NAME)) {
751 name = headers.get(TarGnuSparseKeys.NAME);
752 }
753 if (headers.containsKey(TarGnuSparseKeys.REALSIZE)) {
754 realSize = ParsingUtils.parseIntValue(headers.get(TarGnuSparseKeys.REALSIZE));
755 }
756 }
757
758 void fillStarSparseData(final Map<String, String> headers) throws IOException {
759 starSparse = true;
760 if (headers.containsKey("SCHILY.realsize")) {
761 realSize = ParsingUtils.parseLongValue(headers.get("SCHILY.realsize"));
762 }
763 }
764
765
766
767
768
769
770
771 public FileTime getCreationTime() {
772 return birthTime;
773 }
774
775
776
777
778
779
780 @Override
781 public long getDataOffset() {
782 return dataOffset;
783 }
784
785
786
787
788
789
790
791 public int getDevMajor() {
792 return devMajor;
793 }
794
795
796
797
798
799
800
801 public int getDevMinor() {
802 return devMinor;
803 }
804
805
806
807
808
809
810
811
812
813
814 public TarArchiveEntry[] getDirectoryEntries() {
815 if (file == null || !isDirectory()) {
816 return EMPTY_TAR_ARCHIVE_ENTRY_ARRAY;
817 }
818 final List<TarArchiveEntry> entries = new ArrayList<>();
819 try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(file)) {
820 for (final Path p : dirStream) {
821 entries.add(new TarArchiveEntry(p));
822 }
823 } catch (final IOException e) {
824 return EMPTY_TAR_ARCHIVE_ENTRY_ARRAY;
825 }
826 return entries.toArray(EMPTY_TAR_ARCHIVE_ENTRY_ARRAY);
827 }
828
829
830
831
832
833
834
835
836 public String getExtraPaxHeader(final String name) {
837 return extraPaxHeaders.get(name);
838 }
839
840
841
842
843
844
845
846 public Map<String, String> getExtraPaxHeaders() {
847 return Collections.unmodifiableMap(extraPaxHeaders);
848 }
849
850
851
852
853
854
855
856
857
858
859 public File getFile() {
860 return file != null ? file.toFile() : null;
861 }
862
863
864
865
866
867
868
869 @Deprecated
870 public int getGroupId() {
871 return (int) (groupId & 0xffffffff);
872 }
873
874
875
876
877
878
879 public String getGroupName() {
880 return groupName;
881 }
882
883
884
885
886
887
888
889 public FileTime getLastAccessTime() {
890 return aTime;
891 }
892
893
894
895
896
897
898
899 @Override
900 public Date getLastModifiedDate() {
901 return getModTime();
902 }
903
904
905
906
907
908
909
910 public FileTime getLastModifiedTime() {
911 return mTime;
912 }
913
914
915
916
917
918
919
920 public byte getLinkFlag() {
921 return linkFlag;
922 }
923
924
925
926
927
928
929 public String getLinkName() {
930 return linkName;
931 }
932
933
934
935
936
937
938
939 public long getLongGroupId() {
940 return groupId;
941 }
942
943
944
945
946
947
948
949 public long getLongUserId() {
950 return userId;
951 }
952
953
954
955
956
957
958 public int getMode() {
959 return mode;
960 }
961
962
963
964
965
966
967
968 public Date getModTime() {
969 return FileTimes.toDate(mTime);
970 }
971
972
973
974
975
976
977
978
979
980 @Override
981 public String getName() {
982 return name;
983 }
984
985
986
987
988
989
990
991
992 public List<TarArchiveStructSparse> getOrderedSparseHeaders() throws IOException {
993 if (sparseHeaders == null || sparseHeaders.isEmpty()) {
994 return Collections.emptyList();
995 }
996 final List<TarArchiveStructSparse> orderedAndFiltered = sparseHeaders.stream().filter(s -> s.getOffset() > 0 || s.getNumbytes() > 0)
997 .sorted(Comparator.comparingLong(TarArchiveStructSparse::getOffset)).collect(Collectors.toList());
998 final int numberOfHeaders = orderedAndFiltered.size();
999 for (int i = 0; i < numberOfHeaders; i++) {
1000 final TarArchiveStructSparse str = orderedAndFiltered.get(i);
1001 if (i + 1 < numberOfHeaders && str.getOffset() + str.getNumbytes() > orderedAndFiltered.get(i + 1).getOffset()) {
1002 throw new IOException("Corrupted TAR archive. Sparse blocks for " + getName() + " overlap each other.");
1003 }
1004 if (str.getOffset() + str.getNumbytes() < 0) {
1005
1006 throw new IOException("Unreadable TAR archive. Offset and numbytes for sparse block in " + getName() + " too large.");
1007 }
1008 }
1009 if (!orderedAndFiltered.isEmpty()) {
1010 final TarArchiveStructSparse last = orderedAndFiltered.get(numberOfHeaders - 1);
1011 if (last.getOffset() + last.getNumbytes() > getRealSize()) {
1012 throw new IOException("Corrupted TAR archive. Sparse block extends beyond real size of the entry");
1013 }
1014 }
1015 return orderedAndFiltered;
1016 }
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028 public Path getPath() {
1029 return file;
1030 }
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 public long getRealSize() {
1044 if (!isSparse()) {
1045 return getSize();
1046 }
1047 return realSize;
1048 }
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059 @Override
1060 public long getSize() {
1061 return size;
1062 }
1063
1064
1065
1066
1067
1068
1069
1070 public List<TarArchiveStructSparse> getSparseHeaders() {
1071 return sparseHeaders;
1072 }
1073
1074
1075
1076
1077
1078
1079
1080 public FileTime getStatusChangeTime() {
1081 return cTime;
1082 }
1083
1084
1085
1086
1087
1088
1089
1090 @Deprecated
1091 public int getUserId() {
1092 return (int) (userId & 0xffffffff);
1093 }
1094
1095
1096
1097
1098
1099
1100 public String getUserName() {
1101 return userName;
1102 }
1103
1104
1105
1106
1107
1108
1109 @Override
1110 public int hashCode() {
1111 return getName().hashCode();
1112 }
1113
1114
1115
1116
1117
1118
1119
1120 public boolean isBlockDevice() {
1121 return linkFlag == LF_BLK;
1122 }
1123
1124
1125
1126
1127
1128
1129
1130 public boolean isCharacterDevice() {
1131 return linkFlag == LF_CHR;
1132 }
1133
1134
1135
1136
1137
1138
1139
1140
1141 public boolean isCheckSumOK() {
1142 return checkSumOK;
1143 }
1144
1145
1146
1147
1148
1149
1150
1151 public boolean isDescendent(final TarArchiveEntry desc) {
1152 return desc.getName().startsWith(getName());
1153 }
1154
1155
1156
1157
1158
1159
1160 @Override
1161 public boolean isDirectory() {
1162 if (file != null) {
1163 return Files.isDirectory(file, linkOptions);
1164 }
1165 if (linkFlag == LF_DIR) {
1166 return true;
1167 }
1168 return !isPaxHeader() && !isGlobalPaxHeader() && getName().endsWith("/");
1169 }
1170
1171
1172
1173
1174
1175
1176 public boolean isExtended() {
1177 return isExtended;
1178 }
1179
1180
1181
1182
1183
1184
1185
1186 public boolean isFIFO() {
1187 return linkFlag == LF_FIFO;
1188 }
1189
1190
1191
1192
1193
1194
1195
1196 public boolean isFile() {
1197 if (file != null) {
1198 return Files.isRegularFile(file, linkOptions);
1199 }
1200 if (linkFlag == LF_OLDNORM || linkFlag == LF_NORMAL) {
1201 return true;
1202 }
1203 return linkFlag != LF_DIR && !getName().endsWith("/");
1204 }
1205
1206
1207
1208
1209
1210
1211
1212 public boolean isGlobalPaxHeader() {
1213 return linkFlag == LF_PAX_GLOBAL_EXTENDED_HEADER;
1214 }
1215
1216
1217
1218
1219
1220
1221 public boolean isGNULongLinkEntry() {
1222 return linkFlag == LF_GNUTYPE_LONGLINK;
1223 }
1224
1225
1226
1227
1228
1229
1230 public boolean isGNULongNameEntry() {
1231 return linkFlag == LF_GNUTYPE_LONGNAME;
1232 }
1233
1234
1235
1236
1237
1238
1239 public boolean isGNUSparse() {
1240 return isOldGNUSparse() || isPaxGNUSparse();
1241 }
1242
1243 private boolean isInvalidPrefix(final byte[] header) {
1244
1245 if (header[XSTAR_PREFIX_OFFSET + 130] != 0) {
1246
1247 if (header[LF_OFFSET] != LF_MULTIVOLUME) {
1248 return true;
1249 }
1250
1251
1252
1253 if ((header[XSTAR_MULTIVOLUME_OFFSET] & 0x80) == 0 && header[XSTAR_MULTIVOLUME_OFFSET + 11] != ' ') {
1254 return true;
1255 }
1256 }
1257 return false;
1258 }
1259
1260 private boolean isInvalidXtarTime(final byte[] buffer, final int offset, final int length) {
1261
1262 if ((buffer[offset] & 0x80) == 0) {
1263 final int lastIndex = length - 1;
1264 for (int i = 0; i < lastIndex; i++) {
1265 final byte b = buffer[offset + i];
1266 if (b < '0' || b > '7') {
1267 return true;
1268 }
1269 }
1270
1271 final byte b = buffer[offset + lastIndex];
1272 if (b != ' ' && b != 0) {
1273 return true;
1274 }
1275 }
1276 return false;
1277 }
1278
1279
1280
1281
1282
1283
1284
1285 public boolean isLink() {
1286 return linkFlag == LF_LINK;
1287 }
1288
1289
1290
1291
1292
1293
1294
1295 public boolean isOldGNUSparse() {
1296 return linkFlag == LF_GNUTYPE_SPARSE;
1297 }
1298
1299
1300
1301
1302
1303
1304
1305 public boolean isPaxGNU1XSparse() {
1306 return paxGNU1XSparse;
1307 }
1308
1309
1310
1311
1312
1313
1314
1315 public boolean isPaxGNUSparse() {
1316 return paxGNUSparse;
1317 }
1318
1319
1320
1321
1322
1323
1324
1325 public boolean isPaxHeader() {
1326 return linkFlag == LF_PAX_EXTENDED_HEADER_LC || linkFlag == LF_PAX_EXTENDED_HEADER_UC;
1327 }
1328
1329
1330
1331
1332
1333
1334
1335 public boolean isSparse() {
1336 return isGNUSparse() || isStarSparse();
1337 }
1338
1339
1340
1341
1342
1343
1344
1345 public boolean isStarSparse() {
1346 return starSparse;
1347 }
1348
1349
1350
1351
1352
1353
1354 @Override
1355 public boolean isStreamContiguous() {
1356 return true;
1357 }
1358
1359
1360
1361
1362
1363
1364
1365 public boolean isSymbolicLink() {
1366 return linkFlag == LF_SYMLINK;
1367 }
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387 boolean isTypeFlagUstar() {
1388 return linkFlag == 0 || linkFlag >= '0' && linkFlag <= '7' || linkFlag >= 'A' && linkFlag <= 'Z';
1389 }
1390
1391
1392
1393
1394
1395
1396 private boolean isXstar(final Map<String, String> globalPaxHeaders, final byte[] header) {
1397
1398 if (ArchiveUtils.matchAsciiBuffer(MAGIC_XSTAR, header, XSTAR_MAGIC_OFFSET, XSTAR_MAGIC_LEN)) {
1399 return true;
1400 }
1401
1402
1403
1404
1405
1406
1407 final String archType = globalPaxHeaders.get("SCHILY.archtype");
1408 if (archType != null) {
1409 return "xustar".equals(archType) || "exustar".equals(archType);
1410 }
1411
1412 if (isInvalidPrefix(header) || isInvalidXtarTime(header, XSTAR_ATIME_OFFSET, ATIMELEN_XSTAR)
1413 || isInvalidXtarTime(header, XSTAR_CTIME_OFFSET, CTIMELEN_XSTAR)) {
1414 return false;
1415 }
1416 return true;
1417 }
1418
1419 private long parseOctalOrBinary(final byte[] header, final int offset, final int length, final boolean lenient) {
1420 if (lenient) {
1421 try {
1422 return TarUtils.parseOctalOrBinary(header, offset, length);
1423 } catch (final IllegalArgumentException ex) {
1424 return UNKNOWN;
1425 }
1426 }
1427 return TarUtils.parseOctalOrBinary(header, offset, length);
1428 }
1429
1430
1431
1432
1433
1434
1435
1436 public void parseTarHeader(final byte[] header) {
1437 try {
1438 parseTarHeader(header, TarUtils.DEFAULT_ENCODING);
1439 } catch (final IOException ex) {
1440 try {
1441 parseTarHeader(header, TarUtils.DEFAULT_ENCODING, true, false);
1442 } catch (final IOException ex2) {
1443
1444 throw new UncheckedIOException(ex2);
1445 }
1446 }
1447 }
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458 public void parseTarHeader(final byte[] header, final ZipEncoding encoding) throws IOException {
1459 parseTarHeader(header, encoding, false, false);
1460 }
1461
1462 private void parseTarHeader(final byte[] header, final ZipEncoding encoding, final boolean oldStyle, final boolean lenient) throws IOException {
1463 parseTarHeader(Collections.emptyMap(), header, encoding, oldStyle, lenient);
1464 }
1465
1466 private void parseTarHeader(final Map<String, String> globalPaxHeaders, final byte[] header, final ZipEncoding encoding, final boolean oldStyle,
1467 final boolean lenient) throws IOException {
1468 try {
1469 parseUstarHeaderBlock(globalPaxHeaders, header, encoding, oldStyle, lenient);
1470 } catch (final IllegalArgumentException ex) {
1471 throw new IOException("Corrupted TAR archive.", ex);
1472 }
1473 }
1474
1475 private int parseTarHeaderBlock(final byte[] header, final ZipEncoding encoding, final boolean oldStyle, final boolean lenient, int offset)
1476 throws IOException {
1477 name = oldStyle ? TarUtils.parseName(header, offset, NAMELEN) : TarUtils.parseName(header, offset, NAMELEN, encoding);
1478 offset += NAMELEN;
1479 mode = (int) parseOctalOrBinary(header, offset, MODELEN, lenient);
1480 offset += MODELEN;
1481 userId = (int) parseOctalOrBinary(header, offset, UIDLEN, lenient);
1482 offset += UIDLEN;
1483 groupId = (int) parseOctalOrBinary(header, offset, GIDLEN, lenient);
1484 offset += GIDLEN;
1485 size = TarUtils.parseOctalOrBinary(header, offset, SIZELEN);
1486 if (size < 0) {
1487 throw new IOException("broken archive, entry with negative size");
1488 }
1489 offset += SIZELEN;
1490 mTime = FileTimes.fromUnixTime(parseOctalOrBinary(header, offset, MODTIMELEN, lenient));
1491 offset += MODTIMELEN;
1492 checkSumOK = TarUtils.verifyCheckSum(header);
1493 offset += CHKSUMLEN;
1494 linkFlag = header[offset++];
1495 linkName = oldStyle ? TarUtils.parseName(header, offset, NAMELEN) : TarUtils.parseName(header, offset, NAMELEN, encoding);
1496 return offset;
1497 }
1498
1499 private void parseUstarHeaderBlock(final Map<String, String> globalPaxHeaders, final byte[] header, final ZipEncoding encoding, final boolean oldStyle,
1500 final boolean lenient) throws IOException {
1501 int offset = 0;
1502 offset = parseTarHeaderBlock(header, encoding, oldStyle, lenient, offset);
1503 offset += NAMELEN;
1504 magic = TarUtils.parseName(header, offset, MAGICLEN);
1505 offset += MAGICLEN;
1506 version = TarUtils.parseName(header, offset, VERSIONLEN);
1507 offset += VERSIONLEN;
1508 userName = oldStyle ? TarUtils.parseName(header, offset, UNAMELEN) : TarUtils.parseName(header, offset, UNAMELEN, encoding);
1509 offset += UNAMELEN;
1510 groupName = oldStyle ? TarUtils.parseName(header, offset, GNAMELEN) : TarUtils.parseName(header, offset, GNAMELEN, encoding);
1511 offset += GNAMELEN;
1512 if (linkFlag == LF_CHR || linkFlag == LF_BLK) {
1513 devMajor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);
1514 offset += DEVLEN;
1515 devMinor = (int) parseOctalOrBinary(header, offset, DEVLEN, lenient);
1516 offset += DEVLEN;
1517 } else {
1518 offset += 2 * DEVLEN;
1519 }
1520 final int type = evaluateType(globalPaxHeaders, header);
1521 switch (type) {
1522 case FORMAT_OLDGNU: {
1523 aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_GNU, lenient));
1524 offset += ATIMELEN_GNU;
1525 cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_GNU, lenient));
1526 offset += CTIMELEN_GNU;
1527 offset += OFFSETLEN_GNU;
1528 offset += LONGNAMESLEN_GNU;
1529 offset += PAD2LEN_GNU;
1530 sparseHeaders = new ArrayList<>(TarUtils.readSparseStructs(header, offset, SPARSE_HEADERS_IN_OLDGNU_HEADER));
1531 offset += SPARSELEN_GNU;
1532 isExtended = TarUtils.parseBoolean(header, offset);
1533 offset += ISEXTENDEDLEN_GNU;
1534 realSize = TarUtils.parseOctal(header, offset, REALSIZELEN_GNU);
1535 offset += REALSIZELEN_GNU;
1536 break;
1537 }
1538 case FORMAT_XSTAR: {
1539 final String xstarPrefix = oldStyle ? TarUtils.parseName(header, offset, PREFIXLEN_XSTAR)
1540 : TarUtils.parseName(header, offset, PREFIXLEN_XSTAR, encoding);
1541 offset += PREFIXLEN_XSTAR;
1542 if (!xstarPrefix.isEmpty()) {
1543 name = xstarPrefix + "/" + name;
1544 }
1545 aTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, ATIMELEN_XSTAR, lenient));
1546 offset += ATIMELEN_XSTAR;
1547 cTime = fileTimeFromOptionalSeconds(parseOctalOrBinary(header, offset, CTIMELEN_XSTAR, lenient));
1548 offset += CTIMELEN_XSTAR;
1549 break;
1550 }
1551 case FORMAT_POSIX:
1552 default: {
1553 final String prefix = oldStyle ? TarUtils.parseName(header, offset, PREFIXLEN) : TarUtils.parseName(header, offset, PREFIXLEN, encoding);
1554 offset += PREFIXLEN;
1555
1556 if (isDirectory() && !name.endsWith("/")) {
1557 name += "/";
1558 }
1559 if (!prefix.isEmpty()) {
1560 name = prefix + "/" + name;
1561 }
1562 }
1563 }
1564 }
1565
1566
1567
1568
1569
1570
1571
1572
1573 private void processPaxHeader(final String key, final String val) throws IOException {
1574 processPaxHeader(key, val, extraPaxHeaders);
1575 }
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586 private void processPaxHeader(final String key, final String val, final Map<String, String> headers) throws IOException {
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597 switch (key) {
1598 case "path":
1599 setName(val);
1600 break;
1601 case "linkpath":
1602 setLinkName(val);
1603 break;
1604 case "gid":
1605 setGroupId(ParsingUtils.parseLongValue(val));
1606 break;
1607 case "gname":
1608 setGroupName(val);
1609 break;
1610 case "uid":
1611 setUserId(ParsingUtils.parseLongValue(val));
1612 break;
1613 case "uname":
1614 setUserName(val);
1615 break;
1616 case "size":
1617 final long size = ParsingUtils.parseLongValue(val);
1618 if (size < 0) {
1619 throw new IOException("Corrupted TAR archive. Entry size is negative");
1620 }
1621 setSize(size);
1622 break;
1623 case "mtime":
1624 setLastModifiedTime(FileTime.from(parseInstantFromDecimalSeconds(val)));
1625 break;
1626 case "atime":
1627 setLastAccessTime(FileTime.from(parseInstantFromDecimalSeconds(val)));
1628 break;
1629 case "ctime":
1630 setStatusChangeTime(FileTime.from(parseInstantFromDecimalSeconds(val)));
1631 break;
1632 case "LIBARCHIVE.creationtime":
1633 setCreationTime(FileTime.from(parseInstantFromDecimalSeconds(val)));
1634 break;
1635 case "SCHILY.devminor":
1636 final int devMinor = ParsingUtils.parseIntValue(val);
1637 if (devMinor < 0) {
1638 throw new IOException("Corrupted TAR archive. Dev-Minor is negative");
1639 }
1640 setDevMinor(devMinor);
1641 break;
1642 case "SCHILY.devmajor":
1643 final int devMajor = ParsingUtils.parseIntValue(val);
1644 if (devMajor < 0) {
1645 throw new IOException("Corrupted TAR archive. Dev-Major is negative");
1646 }
1647 setDevMajor(devMajor);
1648 break;
1649 case TarGnuSparseKeys.SIZE:
1650 fillGNUSparse0xData(headers);
1651 break;
1652 case TarGnuSparseKeys.REALSIZE:
1653 fillGNUSparse1xData(headers);
1654 break;
1655 case "SCHILY.filetype":
1656 if ("sparse".equals(val)) {
1657 fillStarSparseData(headers);
1658 }
1659 break;
1660 default:
1661 extraPaxHeaders.put(key, val);
1662 }
1663 }
1664
1665 private void readFileMode(final Path path, final String normalizedName, final LinkOption... options) throws IOException {
1666 if (Files.isDirectory(path, options)) {
1667 this.mode = DEFAULT_DIR_MODE;
1668 this.linkFlag = LF_DIR;
1669
1670 final int nameLength = normalizedName.length();
1671 if (nameLength == 0 || normalizedName.charAt(nameLength - 1) != '/') {
1672 this.name = normalizedName + "/";
1673 } else {
1674 this.name = normalizedName;
1675 }
1676 } else {
1677 this.mode = DEFAULT_FILE_MODE;
1678 this.linkFlag = LF_NORMAL;
1679 this.name = normalizedName;
1680 this.size = Files.size(path);
1681 }
1682 }
1683
1684 private void readOsSpecificProperties(final Path path, final LinkOption... options) throws IOException {
1685 final Set<String> availableAttributeViews = path.getFileSystem().supportedFileAttributeViews();
1686 if (availableAttributeViews.contains("posix")) {
1687 final PosixFileAttributes posixFileAttributes = Files.readAttributes(path, PosixFileAttributes.class, options);
1688 setLastModifiedTime(posixFileAttributes.lastModifiedTime());
1689 setCreationTime(posixFileAttributes.creationTime());
1690 setLastAccessTime(posixFileAttributes.lastAccessTime());
1691 this.userName = posixFileAttributes.owner().getName();
1692 this.groupName = posixFileAttributes.group().getName();
1693 if (availableAttributeViews.contains("unix")) {
1694 this.userId = ((Number) Files.getAttribute(path, "unix:uid", options)).longValue();
1695 this.groupId = ((Number) Files.getAttribute(path, "unix:gid", options)).longValue();
1696 try {
1697 setStatusChangeTime((FileTime) Files.getAttribute(path, "unix:ctime", options));
1698 } catch (final IllegalArgumentException ignored) {
1699
1700 }
1701 }
1702 } else {
1703 if (availableAttributeViews.contains("dos")) {
1704 final DosFileAttributes dosFileAttributes = Files.readAttributes(path, DosFileAttributes.class, options);
1705 setLastModifiedTime(dosFileAttributes.lastModifiedTime());
1706 setCreationTime(dosFileAttributes.creationTime());
1707 setLastAccessTime(dosFileAttributes.lastAccessTime());
1708 } else {
1709 final BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class, options);
1710 setLastModifiedTime(basicFileAttributes.lastModifiedTime());
1711 setCreationTime(basicFileAttributes.creationTime());
1712 setLastAccessTime(basicFileAttributes.lastAccessTime());
1713 }
1714 this.userName = Files.getOwner(path, options).getName();
1715 }
1716 }
1717
1718
1719
1720
1721
1722
1723
1724 public void setCreationTime(final FileTime birthTime) {
1725 this.birthTime = birthTime;
1726 }
1727
1728
1729
1730
1731
1732
1733
1734 public void setDataOffset(final long dataOffset) {
1735 if (dataOffset < 0) {
1736 throw new IllegalArgumentException("The offset cannot be smaller than 0");
1737 }
1738 this.dataOffset = dataOffset;
1739 }
1740
1741
1742
1743
1744
1745
1746
1747
1748 public void setDevMajor(final int devNo) {
1749 if (devNo < 0) {
1750 throw new IllegalArgumentException("Major device number is out of range: " + devNo);
1751 }
1752 this.devMajor = devNo;
1753 }
1754
1755
1756
1757
1758
1759
1760
1761
1762 public void setDevMinor(final int devNo) {
1763 if (devNo < 0) {
1764 throw new IllegalArgumentException("Minor device number is out of range: " + devNo);
1765 }
1766 this.devMinor = devNo;
1767 }
1768
1769
1770
1771
1772
1773
1774 public void setGroupId(final int groupId) {
1775 setGroupId((long) groupId);
1776 }
1777
1778
1779
1780
1781
1782
1783
1784 public void setGroupId(final long groupId) {
1785 this.groupId = groupId;
1786 }
1787
1788
1789
1790
1791
1792
1793 public void setGroupName(final String groupName) {
1794 this.groupName = groupName;
1795 }
1796
1797
1798
1799
1800
1801
1802
1803 public void setIds(final int userId, final int groupId) {
1804 setUserId(userId);
1805 setGroupId(groupId);
1806 }
1807
1808
1809
1810
1811
1812
1813
1814 public void setLastAccessTime(final FileTime time) {
1815 aTime = time;
1816 }
1817
1818
1819
1820
1821
1822
1823
1824 public void setLastModifiedTime(final FileTime time) {
1825 mTime = Objects.requireNonNull(time, "time");
1826 }
1827
1828
1829
1830
1831
1832
1833
1834 public void setLinkName(final String link) {
1835 this.linkName = link;
1836 }
1837
1838
1839
1840
1841
1842
1843 public void setMode(final int mode) {
1844 this.mode = mode;
1845 }
1846
1847
1848
1849
1850
1851
1852
1853 public void setModTime(final Date time) {
1854 setLastModifiedTime(FileTimes.toFileTime(time));
1855 }
1856
1857
1858
1859
1860
1861
1862
1863
1864 public void setModTime(final FileTime time) {
1865 setLastModifiedTime(time);
1866 }
1867
1868
1869
1870
1871
1872
1873
1874 public void setModTime(final long time) {
1875 setLastModifiedTime(FileTime.fromMillis(time));
1876 }
1877
1878
1879
1880
1881
1882
1883 public void setName(final String name) {
1884 this.name = normalizeFileName(name, this.preserveAbsolutePath);
1885 }
1886
1887
1888
1889
1890
1891
1892
1893 public void setNames(final String userName, final String groupName) {
1894 setUserName(userName);
1895 setGroupName(groupName);
1896 }
1897
1898
1899
1900
1901
1902
1903
1904 public void setSize(final long size) {
1905 if (size < 0) {
1906 throw new IllegalArgumentException("Size is out of range: " + size);
1907 }
1908 this.size = size;
1909 }
1910
1911
1912
1913
1914
1915
1916
1917 public void setSparseHeaders(final List<TarArchiveStructSparse> sparseHeaders) {
1918 this.sparseHeaders = sparseHeaders;
1919 }
1920
1921
1922
1923
1924
1925
1926
1927 public void setStatusChangeTime(final FileTime time) {
1928 cTime = time;
1929 }
1930
1931
1932
1933
1934
1935
1936 public void setUserId(final int userId) {
1937 setUserId((long) userId);
1938 }
1939
1940
1941
1942
1943
1944
1945
1946 public void setUserId(final long userId) {
1947 this.userId = userId;
1948 }
1949
1950
1951
1952
1953
1954
1955 public void setUserName(final String userName) {
1956 this.userName = userName;
1957 }
1958
1959
1960
1961
1962
1963
1964 @Override
1965 public String toString() {
1966 return getClass().getSimpleName() + "[" + name + "]";
1967 }
1968
1969
1970
1971
1972
1973
1974
1975 void updateEntryFromPaxHeaders(final Map<String, String> headers) throws IOException {
1976 for (final Map.Entry<String, String> ent : headers.entrySet()) {
1977 processPaxHeader(ent.getKey(), ent.getValue(), headers);
1978 }
1979 }
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989 public void writeEntryHeader(final byte[] outbuf) {
1990 try {
1991 writeEntryHeader(outbuf, TarUtils.DEFAULT_ENCODING, false);
1992 } catch (final IOException ex) {
1993 try {
1994 writeEntryHeader(outbuf, TarUtils.FALLBACK_ENCODING, false);
1995 } catch (final IOException ex2) {
1996
1997 throw new UncheckedIOException(ex2);
1998 }
1999 }
2000 }
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012 public void writeEntryHeader(final byte[] outbuf, final ZipEncoding encoding, final boolean starMode) throws IOException {
2013 int offset = 0;
2014 offset = TarUtils.formatNameBytes(name, outbuf, offset, NAMELEN, encoding);
2015 offset = writeEntryHeaderField(mode, outbuf, offset, MODELEN, starMode);
2016 offset = writeEntryHeaderField(userId, outbuf, offset, UIDLEN, starMode);
2017 offset = writeEntryHeaderField(groupId, outbuf, offset, GIDLEN, starMode);
2018 offset = writeEntryHeaderField(size, outbuf, offset, SIZELEN, starMode);
2019 final FileTime fileTime = mTime;
2020 offset = writeEntryHeaderField(FileTimes.toUnixTime(fileTime), outbuf, offset, MODTIMELEN, starMode);
2021 final int csOffset = offset;
2022 offset = fill((byte) ' ', offset, outbuf, CHKSUMLEN);
2023 outbuf[offset++] = linkFlag;
2024 offset = TarUtils.formatNameBytes(linkName, outbuf, offset, NAMELEN, encoding);
2025 offset = TarUtils.formatNameBytes(magic, outbuf, offset, MAGICLEN);
2026 offset = TarUtils.formatNameBytes(version, outbuf, offset, VERSIONLEN);
2027 offset = TarUtils.formatNameBytes(userName, outbuf, offset, UNAMELEN, encoding);
2028 offset = TarUtils.formatNameBytes(groupName, outbuf, offset, GNAMELEN, encoding);
2029 offset = writeEntryHeaderField(devMajor, outbuf, offset, DEVLEN, starMode);
2030 offset = writeEntryHeaderField(devMinor, outbuf, offset, DEVLEN, starMode);
2031 if (starMode) {
2032
2033 offset = fill(0, offset, outbuf, PREFIXLEN_XSTAR);
2034 offset = writeEntryHeaderOptionalTimeField(aTime, offset, outbuf, ATIMELEN_XSTAR);
2035 offset = writeEntryHeaderOptionalTimeField(cTime, offset, outbuf, CTIMELEN_XSTAR);
2036
2037 offset = fill(0, offset, outbuf, 8);
2038
2039
2040 offset = fill(0, offset, outbuf, XSTAR_MAGIC_LEN);
2041 }
2042 offset = fill(0, offset, outbuf, outbuf.length - offset);
2043 final long chk = TarUtils.computeCheckSum(outbuf);
2044 TarUtils.formatCheckSumOctalBytes(chk, outbuf, csOffset, CHKSUMLEN);
2045 }
2046
2047 private int writeEntryHeaderField(final long value, final byte[] outbuf, final int offset, final int length, final boolean starMode) {
2048 if (!starMode && (value < 0 || value >= 1L << 3 * (length - 1))) {
2049
2050
2051
2052 return TarUtils.formatLongOctalBytes(0, outbuf, offset, length);
2053 }
2054 return TarUtils.formatLongOctalOrBinaryBytes(value, outbuf, offset, length);
2055 }
2056
2057 private int writeEntryHeaderOptionalTimeField(final FileTime time, int offset, final byte[] outbuf, final int fieldLength) {
2058 if (time != null) {
2059 offset = writeEntryHeaderField(FileTimes.toUnixTime(time), outbuf, offset, fieldLength, true);
2060 } else {
2061 offset = fill(0, offset, outbuf, fieldLength);
2062 }
2063 return offset;
2064 }
2065
2066 }