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