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