001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.commons.compress.archivers.tar; 020 021import static java.nio.charset.StandardCharsets.UTF_8; 022 023import java.io.File; 024import java.io.IOException; 025import java.io.OutputStream; 026import java.io.StringWriter; 027import java.math.BigDecimal; 028import java.math.RoundingMode; 029import java.nio.ByteBuffer; 030import java.nio.file.LinkOption; 031import java.nio.file.Path; 032import java.nio.file.attribute.FileTime; 033import java.time.Instant; 034import java.util.Arrays; 035import java.util.HashMap; 036import java.util.Map; 037import java.util.concurrent.TimeUnit; 038 039import org.apache.commons.compress.archivers.ArchiveEntry; 040import org.apache.commons.compress.archivers.ArchiveOutputStream; 041import org.apache.commons.compress.archivers.zip.ZipEncoding; 042import org.apache.commons.compress.archivers.zip.ZipEncodingHelper; 043import org.apache.commons.compress.utils.CountingOutputStream; 044import org.apache.commons.compress.utils.ExactMath; 045import org.apache.commons.compress.utils.FixedLengthBlockOutputStream; 046 047/** 048 * The TarOutputStream writes a UNIX tar archive as an OutputStream. Methods are provided to put 049 * entries, and then write their contents by writing to this stream using write(). 050 * 051 * <p>tar archives consist of a sequence of records of 512 bytes each 052 * that are grouped into blocks. Prior to Apache Commons Compress 1.14 053 * it has been possible to configure a record size different from 512 054 * bytes and arbitrary block sizes. Starting with Compress 1.15 512 is 055 * the only valid option for the record size and the block size must 056 * be a multiple of 512. Also the default block size changed from 057 * 10240 bytes prior to Compress 1.15 to 512 bytes with Compress 058 * 1.15.</p> 059 * 060 * @NotThreadSafe 061 */ 062public class TarArchiveOutputStream extends ArchiveOutputStream { 063 064 /** 065 * Fail if a long file name is required in the archive. 066 */ 067 public static final int LONGFILE_ERROR = 0; 068 069 /** 070 * Long paths will be truncated in the archive. 071 */ 072 public static final int LONGFILE_TRUNCATE = 1; 073 074 /** 075 * GNU tar extensions are used to store long file names in the archive. 076 */ 077 public static final int LONGFILE_GNU = 2; 078 079 /** 080 * POSIX/PAX extensions are used to store long file names in the archive. 081 */ 082 public static final int LONGFILE_POSIX = 3; 083 084 /** 085 * Fail if a big number (e.g. size > 8GiB) is required in the archive. 086 */ 087 public static final int BIGNUMBER_ERROR = 0; 088 089 /** 090 * star/GNU tar/BSD tar extensions are used to store big number in the archive. 091 */ 092 public static final int BIGNUMBER_STAR = 1; 093 094 /** 095 * POSIX/PAX extensions are used to store big numbers in the archive. 096 */ 097 public static final int BIGNUMBER_POSIX = 2; 098 private static final int RECORD_SIZE = 512; 099 100 private long currSize; 101 private String currName; 102 private long currBytes; 103 private final byte[] recordBuf; 104 private int longFileMode = LONGFILE_ERROR; 105 private int bigNumberMode = BIGNUMBER_ERROR; 106 private int recordsWritten; 107 private final int recordsPerBlock; 108 109 private boolean closed; 110 111 /** 112 * Indicates if putArchiveEntry has been called without closeArchiveEntry 113 */ 114 private boolean haveUnclosedEntry; 115 116 /** 117 * indicates if this archive is finished 118 */ 119 private boolean finished; 120 121 private final FixedLengthBlockOutputStream out; 122 private final CountingOutputStream countingOut; 123 124 private final ZipEncoding zipEncoding; 125 126 // the provided encoding (for unit tests) 127 final String encoding; 128 129 private boolean addPaxHeadersForNonAsciiNames; 130 private static final ZipEncoding ASCII = 131 ZipEncodingHelper.getZipEncoding("ASCII"); 132 133 private static final int BLOCK_SIZE_UNSPECIFIED = -511; 134 135 /** 136 * Constructor for TarArchiveOutputStream. 137 * 138 * <p>Uses a block size of 512 bytes.</p> 139 * 140 * @param os the output stream to use 141 */ 142 public TarArchiveOutputStream(final OutputStream os) { 143 this(os, BLOCK_SIZE_UNSPECIFIED); 144 } 145 146 /** 147 * Constructor for TarArchiveOutputStream. 148 * 149 * <p>Uses a block size of 512 bytes.</p> 150 * 151 * @param os the output stream to use 152 * @param encoding name of the encoding to use for file names 153 * @since 1.4 154 */ 155 public TarArchiveOutputStream(final OutputStream os, final String encoding) { 156 this(os, BLOCK_SIZE_UNSPECIFIED, encoding); 157 } 158 159 /** 160 * Constructor for TarArchiveOutputStream. 161 * 162 * @param os the output stream to use 163 * @param blockSize the block size to use. Must be a multiple of 512 bytes. 164 */ 165 public TarArchiveOutputStream(final OutputStream os, final int blockSize) { 166 this(os, blockSize, null); 167 } 168 169 170 /** 171 * Constructor for TarArchiveOutputStream. 172 * 173 * @param os the output stream to use 174 * @param blockSize the block size to use 175 * @param recordSize the record size to use. Must be 512 bytes. 176 * @deprecated recordSize must always be 512 bytes. An IllegalArgumentException will be thrown 177 * if any other value is used 178 */ 179 @Deprecated 180 public TarArchiveOutputStream(final OutputStream os, final int blockSize, 181 final int recordSize) { 182 this(os, blockSize, recordSize, null); 183 } 184 185 /** 186 * Constructor for TarArchiveOutputStream. 187 * 188 * @param os the output stream to use 189 * @param blockSize the block size to use . Must be a multiple of 512 bytes. 190 * @param recordSize the record size to use. Must be 512 bytes. 191 * @param encoding name of the encoding to use for file names 192 * @since 1.4 193 * @deprecated recordSize must always be 512 bytes. An IllegalArgumentException will be thrown 194 * if any other value is used. 195 */ 196 @Deprecated 197 public TarArchiveOutputStream(final OutputStream os, final int blockSize, 198 final int recordSize, final String encoding) { 199 this(os, blockSize, encoding); 200 if (recordSize != RECORD_SIZE) { 201 throw new IllegalArgumentException( 202 "Tar record size must always be 512 bytes. Attempt to set size of " + recordSize); 203 } 204 205 } 206 207 /** 208 * Constructor for TarArchiveOutputStream. 209 * 210 * @param os the output stream to use 211 * @param blockSize the block size to use. Must be a multiple of 512 bytes. 212 * @param encoding name of the encoding to use for file names 213 * @since 1.4 214 */ 215 public TarArchiveOutputStream(final OutputStream os, final int blockSize, 216 final String encoding) { 217 final int realBlockSize; 218 if (BLOCK_SIZE_UNSPECIFIED == blockSize) { 219 realBlockSize = RECORD_SIZE; 220 } else { 221 realBlockSize = blockSize; 222 } 223 224 if (realBlockSize <= 0 || realBlockSize % RECORD_SIZE != 0) { 225 throw new IllegalArgumentException("Block size must be a multiple of 512 bytes. Attempt to use set size of " + blockSize); 226 } 227 out = new FixedLengthBlockOutputStream(countingOut = new CountingOutputStream(os), 228 RECORD_SIZE); 229 this.encoding = encoding; 230 this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding); 231 232 this.recordBuf = new byte[RECORD_SIZE]; 233 this.recordsPerBlock = realBlockSize / RECORD_SIZE; 234 } 235 236 /** 237 * Set the long file mode. This can be LONGFILE_ERROR(0), LONGFILE_TRUNCATE(1), LONGFILE_GNU(2) or 238 * LONGFILE_POSIX(3). This specifies the treatment of long file names (names >= 239 * TarConstants.NAMELEN). Default is LONGFILE_ERROR. 240 * 241 * @param longFileMode the mode to use 242 */ 243 public void setLongFileMode(final int longFileMode) { 244 this.longFileMode = longFileMode; 245 } 246 247 /** 248 * Set the big number mode. This can be BIGNUMBER_ERROR(0), BIGNUMBER_STAR(1) or 249 * BIGNUMBER_POSIX(2). This specifies the treatment of big files (sizes > 250 * TarConstants.MAXSIZE) and other numeric values too big to fit into a traditional tar header. 251 * Default is BIGNUMBER_ERROR. 252 * 253 * @param bigNumberMode the mode to use 254 * @since 1.4 255 */ 256 public void setBigNumberMode(final int bigNumberMode) { 257 this.bigNumberMode = bigNumberMode; 258 } 259 260 /** 261 * Whether to add a PAX extension header for non-ASCII file names. 262 * 263 * @param b whether to add a PAX extension header for non-ASCII file names. 264 * @since 1.4 265 */ 266 public void setAddPaxHeadersForNonAsciiNames(final boolean b) { 267 addPaxHeadersForNonAsciiNames = b; 268 } 269 270 @Deprecated 271 @Override 272 public int getCount() { 273 return (int) getBytesWritten(); 274 } 275 276 @Override 277 public long getBytesWritten() { 278 return countingOut.getBytesWritten(); 279 } 280 281 /** 282 * Ends the TAR archive without closing the underlying OutputStream. 283 * 284 * An archive consists of a series of file entries terminated by an 285 * end-of-archive entry, which consists of two 512 blocks of zero bytes. 286 * POSIX.1 requires two EOF records, like some other implementations. 287 * 288 * @throws IOException on error 289 */ 290 @Override 291 public void finish() throws IOException { 292 if (finished) { 293 throw new IOException("This archive has already been finished"); 294 } 295 296 if (haveUnclosedEntry) { 297 throw new IOException("This archive contains unclosed entries."); 298 } 299 writeEOFRecord(); 300 writeEOFRecord(); 301 padAsNeeded(); 302 out.flush(); 303 finished = true; 304 } 305 306 /** 307 * Closes the underlying OutputStream. 308 * 309 * @throws IOException on error 310 */ 311 @Override 312 public void close() throws IOException { 313 try { 314 if (!finished) { 315 finish(); 316 } 317 } finally { 318 if (!closed) { 319 out.close(); 320 closed = true; 321 } 322 } 323 } 324 325 /** 326 * Get the record size being used by this stream's TarBuffer. 327 * 328 * @return The TarBuffer record size. 329 * @deprecated 330 */ 331 @Deprecated 332 public int getRecordSize() { 333 return RECORD_SIZE; 334 } 335 336 /** 337 * Put an entry on the output stream. This writes the entry's header record and positions the 338 * output stream for writing the contents of the entry. Once this method is called, the stream 339 * is ready for calls to write() to write the entry's contents. Once the contents are written, 340 * closeArchiveEntry() <B>MUST</B> be called to ensure that all buffered data is completely 341 * written to the output stream. 342 * 343 * @param archiveEntry The TarEntry to be written to the archive. 344 * @throws IOException on error 345 * @throws ClassCastException if archiveEntry is not an instance of TarArchiveEntry 346 * @throws IllegalArgumentException if the {@link TarArchiveOutputStream#longFileMode} equals 347 * {@link TarArchiveOutputStream#LONGFILE_ERROR} and the file 348 * name is too long 349 * @throws IllegalArgumentException if the {@link TarArchiveOutputStream#bigNumberMode} equals 350 * {@link TarArchiveOutputStream#BIGNUMBER_ERROR} and one of the numeric values 351 * exceeds the limits of a traditional tar header. 352 */ 353 @Override 354 public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { 355 if (finished) { 356 throw new IOException("Stream has already been finished"); 357 } 358 final TarArchiveEntry entry = (TarArchiveEntry) archiveEntry; 359 if (entry.isGlobalPaxHeader()) { 360 final byte[] data = encodeExtendedPaxHeadersContents(entry.getExtraPaxHeaders()); 361 entry.setSize(data.length); 362 entry.writeEntryHeader(recordBuf, zipEncoding, bigNumberMode == BIGNUMBER_STAR); 363 writeRecord(recordBuf); 364 currSize= entry.getSize(); 365 currBytes = 0; 366 this.haveUnclosedEntry = true; 367 write(data); 368 closeArchiveEntry(); 369 } else { 370 final Map<String, String> paxHeaders = new HashMap<>(); 371 final String entryName = entry.getName(); 372 final boolean paxHeaderContainsPath = handleLongName(entry, entryName, paxHeaders, "path", 373 TarConstants.LF_GNUTYPE_LONGNAME, "file name"); 374 final String linkName = entry.getLinkName(); 375 final boolean paxHeaderContainsLinkPath = linkName != null && !linkName.isEmpty() 376 && handleLongName(entry, linkName, paxHeaders, "linkpath", 377 TarConstants.LF_GNUTYPE_LONGLINK, "link name"); 378 379 if (bigNumberMode == BIGNUMBER_POSIX) { 380 addPaxHeadersForBigNumbers(paxHeaders, entry); 381 } else if (bigNumberMode != BIGNUMBER_STAR) { 382 failForBigNumbers(entry); 383 } 384 385 if (addPaxHeadersForNonAsciiNames && !paxHeaderContainsPath 386 && !ASCII.canEncode(entryName)) { 387 paxHeaders.put("path", entryName); 388 } 389 390 if (addPaxHeadersForNonAsciiNames && !paxHeaderContainsLinkPath 391 && (entry.isLink() || entry.isSymbolicLink()) 392 && !ASCII.canEncode(linkName)) { 393 paxHeaders.put("linkpath", linkName); 394 } 395 paxHeaders.putAll(entry.getExtraPaxHeaders()); 396 397 if (!paxHeaders.isEmpty()) { 398 writePaxHeaders(entry, entryName, paxHeaders); 399 } 400 401 entry.writeEntryHeader(recordBuf, zipEncoding, bigNumberMode == BIGNUMBER_STAR); 402 writeRecord(recordBuf); 403 404 currBytes = 0; 405 406 if (entry.isDirectory()) { 407 currSize = 0; 408 } else { 409 currSize = entry.getSize(); 410 } 411 currName = entryName; 412 haveUnclosedEntry = true; 413 } 414 } 415 416 /** 417 * Close an entry. This method MUST be called for all file entries that contain data. The reason 418 * is that we must buffer data written to the stream in order to satisfy the buffer's record 419 * based writes. Thus, there may be data fragments still being assembled that must be written to 420 * the output stream before this entry is closed and the next entry written. 421 * 422 * @throws IOException on error 423 */ 424 @Override 425 public void closeArchiveEntry() throws IOException { 426 if (finished) { 427 throw new IOException("Stream has already been finished"); 428 } 429 if (!haveUnclosedEntry) { 430 throw new IOException("No current entry to close"); 431 } 432 out.flushBlock(); 433 if (currBytes < currSize) { 434 throw new IOException("Entry '" + currName + "' closed at '" 435 + currBytes 436 + "' before the '" + currSize 437 + "' bytes specified in the header were written"); 438 } 439 recordsWritten = ExactMath.add(recordsWritten, (currSize / RECORD_SIZE)); 440 441 if (0 != currSize % RECORD_SIZE) { 442 recordsWritten++; 443 } 444 haveUnclosedEntry = false; 445 } 446 447 /** 448 * Writes bytes to the current tar archive entry. This method is aware of the current entry and 449 * will throw an exception if you attempt to write bytes past the length specified for the 450 * current entry. 451 * 452 * @param wBuf The buffer to write to the archive. 453 * @param wOffset The offset in the buffer from which to get bytes. 454 * @param numToWrite The number of bytes to write. 455 * @throws IOException on error 456 */ 457 @Override 458 public void write(final byte[] wBuf, final int wOffset, final int numToWrite) throws IOException { 459 if (!haveUnclosedEntry) { 460 throw new IllegalStateException("No current tar entry"); 461 } 462 if (currBytes + numToWrite > currSize) { 463 throw new IOException("Request to write '" + numToWrite 464 + "' bytes exceeds size in header of '" 465 + currSize + "' bytes for entry '" 466 + currName + "'"); 467 } 468 out.write(wBuf, wOffset, numToWrite); 469 currBytes += numToWrite; 470 } 471 472 /** 473 * Writes a PAX extended header with the given map as contents. 474 * 475 * @since 1.4 476 */ 477 void writePaxHeaders(final TarArchiveEntry entry, 478 final String entryName, 479 final Map<String, String> headers) throws IOException { 480 String name = "./PaxHeaders.X/" + stripTo7Bits(entryName); 481 if (name.length() >= TarConstants.NAMELEN) { 482 name = name.substring(0, TarConstants.NAMELEN - 1); 483 } 484 final TarArchiveEntry pex = new TarArchiveEntry(name, 485 TarConstants.LF_PAX_EXTENDED_HEADER_LC); 486 transferModTime(entry, pex); 487 488 final byte[] data = encodeExtendedPaxHeadersContents(headers); 489 pex.setSize(data.length); 490 putArchiveEntry(pex); 491 write(data); 492 closeArchiveEntry(); 493 } 494 495 private byte[] encodeExtendedPaxHeadersContents(final Map<String, String> headers) { 496 final StringWriter w = new StringWriter(); 497 headers.forEach((k, v) -> { 498 int len = k.length() + v.length() 499 + 3 /* blank, equals and newline */ 500 + 2 /* guess 9 < actual length < 100 */; 501 String line = len + " " + k + "=" + v + "\n"; 502 int actualLength = line.getBytes(UTF_8).length; 503 while (len != actualLength) { 504 // Adjust for cases where length < 10 or > 100 505 // or where UTF-8 encoding isn't a single octet 506 // per character. 507 // Must be in loop as size may go from 99 to 100 in 508 // first pass so we'd need a second. 509 len = actualLength; 510 line = len + " " + k + "=" + v + "\n"; 511 actualLength = line.getBytes(UTF_8).length; 512 } 513 w.write(line); 514 }); 515 return w.toString().getBytes(UTF_8); 516 } 517 518 private String stripTo7Bits(final String name) { 519 final int length = name.length(); 520 final StringBuilder result = new StringBuilder(length); 521 for (int i = 0; i < length; i++) { 522 final char stripped = (char) (name.charAt(i) & 0x7F); 523 if (shouldBeReplaced(stripped)) { 524 result.append("_"); 525 } else { 526 result.append(stripped); 527 } 528 } 529 return result.toString(); 530 } 531 532 /** 533 * @return true if the character could lead to problems when used inside a TarArchiveEntry name 534 * for a PAX header. 535 */ 536 private boolean shouldBeReplaced(final char c) { 537 return c == 0 // would be read as Trailing null 538 || c == '/' // when used as last character TAE will consider the PAX header a directory 539 || c == '\\'; // same as '/' as slashes get "normalized" on Windows 540 } 541 542 /** 543 * Write an EOF (end of archive) record to the tar archive. An EOF record consists of a record 544 * of all zeros. 545 */ 546 private void writeEOFRecord() throws IOException { 547 Arrays.fill(recordBuf, (byte) 0); 548 writeRecord(recordBuf); 549 } 550 551 @Override 552 public void flush() throws IOException { 553 out.flush(); 554 } 555 556 @Override 557 public ArchiveEntry createArchiveEntry(final File inputFile, final String entryName) 558 throws IOException { 559 if (finished) { 560 throw new IOException("Stream has already been finished"); 561 } 562 return new TarArchiveEntry(inputFile, entryName); 563 } 564 565 @Override 566 public ArchiveEntry createArchiveEntry(final Path inputPath, final String entryName, final LinkOption... options) throws IOException { 567 if (finished) { 568 throw new IOException("Stream has already been finished"); 569 } 570 return new TarArchiveEntry(inputPath, entryName, options); 571 } 572 573 /** 574 * Write an archive record to the archive. 575 * 576 * @param record The record data to write to the archive. 577 * @throws IOException on error 578 */ 579 private void writeRecord(final byte[] record) throws IOException { 580 if (record.length != RECORD_SIZE) { 581 throw new IOException("Record to write has length '" 582 + record.length 583 + "' which is not the record size of '" 584 + RECORD_SIZE + "'"); 585 } 586 587 out.write(record); 588 recordsWritten++; 589 } 590 591 private void padAsNeeded() throws IOException { 592 final int start = recordsWritten % recordsPerBlock; 593 if (start != 0) { 594 for (int i = start; i < recordsPerBlock; i++) { 595 writeEOFRecord(); 596 } 597 } 598 } 599 600 private void addPaxHeadersForBigNumbers(final Map<String, String> paxHeaders, 601 final TarArchiveEntry entry) { 602 addPaxHeaderForBigNumber(paxHeaders, "size", entry.getSize(), 603 TarConstants.MAXSIZE); 604 addPaxHeaderForBigNumber(paxHeaders, "gid", entry.getLongGroupId(), 605 TarConstants.MAXID); 606 addFileTimePaxHeaderForBigNumber(paxHeaders, "mtime", 607 entry.getLastModifiedTime(), TarConstants.MAXSIZE); 608 addFileTimePaxHeader(paxHeaders, "atime", entry.getLastAccessTime()); 609 if (entry.getStatusChangeTime() != null) { 610 addFileTimePaxHeader(paxHeaders, "ctime", entry.getStatusChangeTime()); 611 } else { 612 // ctime is usually set from creation time on platforms where the real ctime is not available 613 addFileTimePaxHeader(paxHeaders, "ctime", entry.getCreationTime()); 614 } 615 addPaxHeaderForBigNumber(paxHeaders, "uid", entry.getLongUserId(), 616 TarConstants.MAXID); 617 // libarchive extensions 618 addFileTimePaxHeader(paxHeaders, "LIBARCHIVE.creationtime", entry.getCreationTime()); 619 // star extensions by Jörg Schilling 620 addPaxHeaderForBigNumber(paxHeaders, "SCHILY.devmajor", 621 entry.getDevMajor(), TarConstants.MAXID); 622 addPaxHeaderForBigNumber(paxHeaders, "SCHILY.devminor", 623 entry.getDevMinor(), TarConstants.MAXID); 624 // there is no PAX header for file mode 625 failForBigNumber("mode", entry.getMode(), TarConstants.MAXID); 626 } 627 628 private void addPaxHeaderForBigNumber(final Map<String, String> paxHeaders, 629 final String header, final long value, 630 final long maxValue) { 631 if (value < 0 || value > maxValue) { 632 paxHeaders.put(header, String.valueOf(value)); 633 } 634 } 635 636 private void addFileTimePaxHeaderForBigNumber(final Map<String, String> paxHeaders, 637 final String header, final FileTime value, 638 final long maxValue) { 639 if (value != null) { 640 final Instant instant = value.toInstant(); 641 final long seconds = instant.getEpochSecond(); 642 final int nanos = instant.getNano(); 643 if (nanos == 0) { 644 addPaxHeaderForBigNumber(paxHeaders, header, seconds, maxValue); 645 } else { 646 addInstantPaxHeader(paxHeaders, header, seconds, nanos); 647 } 648 } 649 } 650 651 private void addFileTimePaxHeader(final Map<String, String> paxHeaders, 652 final String header, final FileTime value) { 653 if (value != null) { 654 final Instant instant = value.toInstant(); 655 final long seconds = instant.getEpochSecond(); 656 final int nanos = instant.getNano(); 657 if (nanos == 0) { 658 paxHeaders.put(header, String.valueOf(seconds)); 659 } else { 660 addInstantPaxHeader(paxHeaders, header, seconds, nanos); 661 } 662 } 663 } 664 665 private void addInstantPaxHeader(final Map<String, String> paxHeaders, 666 final String header, final long seconds, final int nanos) { 667 final BigDecimal bdSeconds = BigDecimal.valueOf(seconds); 668 final BigDecimal bdNanos = BigDecimal.valueOf(nanos).movePointLeft(9).setScale(7, RoundingMode.DOWN); 669 final BigDecimal timestamp = bdSeconds.add(bdNanos); 670 paxHeaders.put(header, timestamp.toPlainString()); 671 } 672 673 private void failForBigNumbers(final TarArchiveEntry entry) { 674 failForBigNumber("entry size", entry.getSize(), TarConstants.MAXSIZE); 675 failForBigNumberWithPosixMessage("group id", entry.getLongGroupId(), TarConstants.MAXID); 676 failForBigNumber("last modification time", 677 entry.getLastModifiedTime().to(TimeUnit.SECONDS), 678 TarConstants.MAXSIZE); 679 failForBigNumber("user id", entry.getLongUserId(), TarConstants.MAXID); 680 failForBigNumber("mode", entry.getMode(), TarConstants.MAXID); 681 failForBigNumber("major device number", entry.getDevMajor(), 682 TarConstants.MAXID); 683 failForBigNumber("minor device number", entry.getDevMinor(), 684 TarConstants.MAXID); 685 } 686 687 private void failForBigNumber(final String field, final long value, final long maxValue) { 688 failForBigNumber(field, value, maxValue, ""); 689 } 690 691 private void failForBigNumberWithPosixMessage(final String field, final long value, 692 final long maxValue) { 693 failForBigNumber(field, value, maxValue, 694 " Use STAR or POSIX extensions to overcome this limit"); 695 } 696 697 private void failForBigNumber(final String field, final long value, final long maxValue, 698 final String additionalMsg) { 699 if (value < 0 || value > maxValue) { 700 throw new IllegalArgumentException(field + " '" + value //NOSONAR 701 + "' is too big ( > " 702 + maxValue + " )." + additionalMsg); 703 } 704 } 705 706 /** 707 * Handles long file or link names according to the longFileMode setting. 708 * 709 * <p>I.e. if the given name is too long to be written to a plain tar header then <ul> <li>it 710 * creates a pax header who's name is given by the paxHeaderName parameter if longFileMode is 711 * POSIX</li> <li>it creates a GNU longlink entry who's type is given by the linkType parameter 712 * if longFileMode is GNU</li> <li>it throws an exception if longFileMode is ERROR</li> <li>it 713 * truncates the name if longFileMode is TRUNCATE</li> </ul></p> 714 * 715 * @param entry entry the name belongs to 716 * @param name the name to write 717 * @param paxHeaders current map of pax headers 718 * @param paxHeaderName name of the pax header to write 719 * @param linkType type of the GNU entry to write 720 * @param fieldName the name of the field 721 * @throws IllegalArgumentException if the {@link TarArchiveOutputStream#longFileMode} equals 722 * {@link TarArchiveOutputStream#LONGFILE_ERROR} and the file 723 * name is too long 724 * @return whether a pax header has been written. 725 */ 726 private boolean handleLongName(final TarArchiveEntry entry, final String name, 727 final Map<String, String> paxHeaders, 728 final String paxHeaderName, final byte linkType, final String fieldName) 729 throws IOException { 730 final ByteBuffer encodedName = zipEncoding.encode(name); 731 final int len = encodedName.limit() - encodedName.position(); 732 if (len >= TarConstants.NAMELEN) { 733 734 if (longFileMode == LONGFILE_POSIX) { 735 paxHeaders.put(paxHeaderName, name); 736 return true; 737 } 738 if (longFileMode == LONGFILE_GNU) { 739 // create a TarEntry for the LongLink, the contents 740 // of which are the link's name 741 final TarArchiveEntry longLinkEntry = new TarArchiveEntry(TarConstants.GNU_LONGLINK, 742 linkType); 743 744 longLinkEntry.setSize(len + 1L); // +1 for NUL 745 transferModTime(entry, longLinkEntry); 746 putArchiveEntry(longLinkEntry); 747 write(encodedName.array(), encodedName.arrayOffset(), len); 748 write(0); // NUL terminator 749 closeArchiveEntry(); 750 } else if (longFileMode != LONGFILE_TRUNCATE) { 751 throw new IllegalArgumentException(fieldName + " '" + name //NOSONAR 752 + "' is too long ( > " 753 + TarConstants.NAMELEN + " bytes)"); 754 } 755 } 756 return false; 757 } 758 759 private void transferModTime(final TarArchiveEntry from, final TarArchiveEntry to) { 760 long fromModTimeSeconds = from.getLastModifiedTime().to(TimeUnit.SECONDS); 761 if (fromModTimeSeconds < 0 || fromModTimeSeconds > TarConstants.MAXSIZE) { 762 fromModTimeSeconds = 0; 763 } 764 to.setLastModifiedTime(FileTime.from(fromModTimeSeconds, TimeUnit.SECONDS)); 765 } 766}