    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.ar;
    020
    021import java.io.EOFException;
    022import java.io.IOException;
    023import java.io.InputStream;
    024import java.util.Arrays;
    025
    026import org.apache.commons.compress.archivers.ArchiveEntry;
    027import org.apache.commons.compress.archivers.ArchiveInputStream;
    028import org.apache.commons.compress.utils.ArchiveUtils;
    029import org.apache.commons.compress.utils.IOUtils;
    030
    031/**
    032 * Implements the "ar" archive format as an input stream.
    033 *
    034 * @NotThreadSafe
    035 */
    036public class ArArchiveInputStream extends ArchiveInputStream {
    037
    038    // offsets and length of meta data parts
    039    private static final int NAME_OFFSET = 0;
    040    private static final int NAME_LEN = 16;
    041    private static final int LAST_MODIFIED_OFFSET = NAME_LEN;
    042
    043    private static final int LAST_MODIFIED_LEN = 12;
    044
    045    private static final int USER_ID_OFFSET = LAST_MODIFIED_OFFSET + LAST_MODIFIED_LEN;
    046
    047    private static final int USER_ID_LEN = 6;
    048
    049    private static final int GROUP_ID_OFFSET = USER_ID_OFFSET + USER_ID_LEN;
    050    private static final int GROUP_ID_LEN = 6;
    051    private static final int FILE_MODE_OFFSET = GROUP_ID_OFFSET + GROUP_ID_LEN;
    052    private static final int FILE_MODE_LEN = 8;
    053    private static final int LENGTH_OFFSET = FILE_MODE_OFFSET + FILE_MODE_LEN;
    054    private static final int LENGTH_LEN = 10;
    055    static final String BSD_LONGNAME_PREFIX = "#1/";
    056    private static final int BSD_LONGNAME_PREFIX_LEN =
    057        BSD_LONGNAME_PREFIX.length();
    058    private static final String BSD_LONGNAME_PATTERN =
    059        "^" + BSD_LONGNAME_PREFIX + "\\d+";
    060    private static final String GNU_STRING_TABLE_NAME = "//";
    061    private static final String GNU_LONGNAME_PATTERN = "^/\\d+";
    062    /**
    063     * Does the name look like it is a long name (or a name containing
    064     * spaces) as encoded by BSD ar?
    065     *
    066     * <p>From the FreeBSD ar(5) man page:</p>
    067     * <pre>
    068     * BSD   In the BSD variant, names that are shorter than 16
    069     *       characters and without embedded spaces are stored
    070     *       directly in this field.  If a name has an embedded
    071     *       space, or if it is longer than 16 characters, then
    072     *       the string "#1/" followed by the decimal represen-
    073     *       tation of the length of the file name is placed in
    074     *       this field. The actual file name is stored immedi-
    075     *       ately after the archive header.  The content of the
    076     *       archive member follows the file name.  The ar_size
    077     *       field of the header (see below) will then hold the
    078     *       sum of the size of the file name and the size of
    079     *       the member.
    080     * </pre>
    081     *
    082     * @since 1.3
    083     */
    084    private static boolean isBSDLongName(final String name) {
    085        return name != null && name.matches(BSD_LONGNAME_PATTERN);
    086    }
    087
    088    /**
    089     * Is this the name of the "Archive String Table" as used by
    090     * SVR4/GNU to store long file names?
    091     *
    092     * <p>GNU ar stores multiple extended file names in the data section
    093     * of a file with the name "//", this record is referred to by
    094     * future headers.</p>
    095     *
    096     * <p>A header references an extended file name by storing a "/"
    097     * followed by a decimal offset to the start of the file name in
    098     * the extended file name data section.</p>
    099     *
    100     * <p>The format of the "//" file itself is simply a list of the
    101     * long file names, each separated by one or more LF
    102     * characters. Note that the decimal offsets are number of
    103     * characters, not line or string number within the "//" file.</p>
    104     */
    105    private static boolean isGNUStringTable(final String name) {
    106        return GNU_STRING_TABLE_NAME.equals(name);
    107    }
    108
    109    /**
    110     * Checks if the signature matches ASCII "!&lt;arch&gt;" followed by a single LF
    111     * control character
    112     *
    113     * @param signature
    114     *            the bytes to check
    115     * @param length
    116     *            the number of bytes to check
    117     * @return true, if this stream is an Ar archive stream, false otherwise
    118     */
    119    public static boolean matches(final byte[] signature, final int length) {
    120        // 3c21 7261 6863 0a3e
    121
    122        return length >= 8 && signature[0] == 0x21 &&
    123                signature[1] == 0x3c && signature[2] == 0x61 &&
    124                signature[3] == 0x72 && signature[4] == 0x63 &&
    125                signature[5] == 0x68 && signature[6] == 0x3e &&
    126                signature[7] == 0x0a;
    127    }
    128
    129    private final InputStream input;
    130
    131    private long offset;
    132
    133    private boolean closed;
    134
    135    /*
    136     * If getNextEntry has been called, the entry metadata is stored in
    137     * currentEntry.
    138     */
    139    private ArArchiveEntry currentEntry;
    140
    141    // Storage area for extra long names (GNU ar)
    142    private byte[] namebuffer;
    143
    144    /*
    145     * The offset where the current entry started. -1 if no entry has been
    146     * called
    147     */
    148    private long entryOffset = -1;
    149
    150    // cached buffer for meta data - must only be used locally in the class (COMPRESS-172 - reduce garbage collection)
    151    private final byte[] metaData =
    152        new byte[NAME_LEN + LAST_MODIFIED_LEN + USER_ID_LEN + GROUP_ID_LEN + FILE_MODE_LEN + LENGTH_LEN];
    153
    154    /**
    155     * Constructs an Ar input stream with the referenced stream
    156     *
    157     * @param inputStream
    158     *            the ar input stream
    159     */
    160    public ArArchiveInputStream(final InputStream inputStream) {
    161        this.input = inputStream;
    162    }
    163
    164    private int asInt(final byte[] byteArray, final int offset, final int len) {
    165        return asInt(byteArray, offset, len, 10, false);
    166    }
    167
    168    private int asInt(final byte[] byteArray, final int offset, final int len, final boolean treatBlankAsZero) {
    169        return asInt(byteArray, offset, len, 10, treatBlankAsZero);
    170    }
    171
    172    private int asInt(final byte[] byteArray, final int offset, final int len, final int base) {
    173        return asInt(byteArray, offset, len, base, false);
    174    }
    175
    176    private int asInt(final byte[] byteArray, final int offset, final int len, final int base, final boolean treatBlankAsZero) {
    177        final String string = ArchiveUtils.toAsciiString(byteArray, offset, len).trim();
    178        if (string.isEmpty() && treatBlankAsZero) {
    179            return 0;
    180        }
    181        return Integer.parseInt(string, base);
    182    }
    183    private long asLong(final byte[] byteArray, final int offset, final int len) {
    184        return Long.parseLong(ArchiveUtils.toAsciiString(byteArray, offset, len).trim());
    185    }
    186    /*
    187     * (non-Javadoc)
    188     *
    189     * @see java.io.InputStream#close()
    190     */
    191    @Override
    192    public void close() throws IOException {
    193        if (!closed) {
    194            closed = true;
    195            input.close();
    196        }
    197        currentEntry = null;
    198    }
    199
    200    /**
    201     * Reads the real name from the current stream assuming the very
    202     * first bytes to be read are the real file name.
    203     *
    204     * @see #isBSDLongName
    205     *
    206     * @since 1.3
    207     */
    208    private String getBSDLongName(final String bsdLongName) throws IOException {
    209        final int nameLen =
    210            Integer.parseInt(bsdLongName.substring(BSD_LONGNAME_PREFIX_LEN));
    211        final byte[] name = IOUtils.readRange(input, nameLen);
    212        final int read = name.length;
    213        trackReadBytes(read);
    214        if (read != nameLen) {
    215            throw new EOFException();
    216        }
    217        return ArchiveUtils.toAsciiString(name);
    218    }
    219
    220    /**
    221     * Get an extended name from the GNU extended name buffer.
    222     *
    223     * @param offset pointer to entry within the buffer
    224     * @return the extended file name; without trailing "/" if present.
    225     * @throws IOException if name not found or buffer not set up
    226     */
    227    private String getExtendedName(final int offset) throws IOException {
    228        if (namebuffer == null) {
    229            throw new IOException("Cannot process GNU long filename as no // record was found");
    230        }
    231        for (int i = offset; i < namebuffer.length; i++) {
    232            if (namebuffer[i] == '\012' || namebuffer[i] == 0) {
    233                if (namebuffer[i - 1] == '/') {
    234                    i--; // drop trailing /
    235                }
    236                return ArchiveUtils.toAsciiString(namebuffer, offset, i - offset);
    237            }
    238        }
    239        throw new IOException("Failed to read entry: " + offset);
    240    }
    241
    242    /**
    243     * Returns the next AR entry in this stream.
    244     *
    245     * @return the next AR entry.
    246     * @throws IOException
    247     *             if the entry could not be read
    248     */
    249    public ArArchiveEntry getNextArEntry() throws IOException {
    250        if (currentEntry != null) {
    251            final long entryEnd = entryOffset + currentEntry.getLength();
    252            final long skipped = IOUtils.skip(input, entryEnd - offset);
    253            trackReadBytes(skipped);
    254            currentEntry = null;
    255        }
    256
    257        if (offset == 0) {
    258            final byte[] expected = ArchiveUtils.toAsciiBytes(ArArchiveEntry.HEADER);
    259            final byte[] realized = IOUtils.readRange(input, expected.length);
    260            final int read = realized.length;
    261            trackReadBytes(read);
    262            if (read != expected.length) {
    263                throw new IOException("Failed to read header. Occurred at byte: " + getBytesRead());
    264            }
    265            if (!Arrays.equals(expected, realized)) {
    266                throw new IOException("Invalid header " + ArchiveUtils.toAsciiString(realized));
    267            }
    268        }
    269
    270        if (offset % 2 != 0) {
    271            if (input.read() < 0) {
    272                // hit eof
    273                return null;
    274            }
    275            trackReadBytes(1);
    276        }
    277
    278        {
    279            final int read = IOUtils.readFully(input, metaData);
    280            trackReadBytes(read);
    281            if (read == 0) {
    282                return null;
    283            }
    284            if (read < metaData.length) {
    285                throw new IOException("Truncated ar archive");
    286            }
    287        }
    288
    289        {
    290            final byte[] expected = ArchiveUtils.toAsciiBytes(ArArchiveEntry.TRAILER);
    291            final byte[] realized = IOUtils.readRange(input, expected.length);
    292            final int read = realized.length;
    293            trackReadBytes(read);
    294            if (read != expected.length) {
    295                throw new IOException("Failed to read entry trailer. Occurred at byte: " + getBytesRead());
    296            }
    297            if (!Arrays.equals(expected, realized)) {
    298                throw new IOException("Invalid entry trailer. not read the content? Occurred at byte: " + getBytesRead());
    299            }
    300        }
    301
    302        entryOffset = offset;
    303
    304//        GNU ar uses a '/' to mark the end of the filename; this allows for the use of spaces without the use of an extended filename.
    305
    306        // entry name is stored as ASCII string
    307        String temp = ArchiveUtils.toAsciiString(metaData, NAME_OFFSET, NAME_LEN).trim();
    308        if (isGNUStringTable(temp)) { // GNU extended filenames entry
    309            currentEntry = readGNUStringTable(metaData, LENGTH_OFFSET, LENGTH_LEN);
    310            return getNextArEntry();
    311        }
    312
    313        long len = asLong(metaData, LENGTH_OFFSET, LENGTH_LEN);
    314        if (temp.endsWith("/")) { // GNU terminator
    315            temp = temp.substring(0, temp.length() - 1);
    316        } else if (isGNULongName(temp)) {
    317            final int off = Integer.parseInt(temp.substring(1));// get the offset
    318            temp = getExtendedName(off); // convert to the long name
    319        } else if (isBSDLongName(temp)) {
    320            temp = getBSDLongName(temp);
    321            // entry length contained the length of the file name in
    322            // addition to the real length of the entry.
    323            // assume file name was ASCII, there is no "standard" otherwise
    324            final int nameLen = temp.length();
    325            len -= nameLen;
    326            entryOffset += nameLen;
    327        }
    328
    329        if (len < 0) {
    330            throw new IOException("broken archive, entry with negative size");
    331        }
    332
    333        currentEntry = new ArArchiveEntry(temp, len,
    334                                          asInt(metaData, USER_ID_OFFSET, USER_ID_LEN, true),
    335                                          asInt(metaData, GROUP_ID_OFFSET, GROUP_ID_LEN, true),
    336                                          asInt(metaData, FILE_MODE_OFFSET, FILE_MODE_LEN, 8),
    337                                          asLong(metaData, LAST_MODIFIED_OFFSET, LAST_MODIFIED_LEN));
    338        return currentEntry;
    339    }
    340
    341    /*
    342     * (non-Javadoc)
    343     *
    344     * @see
    345     * org.apache.commons.compress.archivers.ArchiveInputStream#getNextEntry()
    346     */
    347    @Override
    348    public ArchiveEntry getNextEntry() throws IOException {
    349        return getNextArEntry();
    350    }
    351
    352    /**
    353     * Does the name look like it is a long name (or a name containing
    354     * spaces) as encoded by SVR4/GNU ar?
    355     *
    356     * @see #isGNUStringTable
    357     */
    358    private boolean isGNULongName(final String name) {
    359        return name != null && name.matches(GNU_LONGNAME_PATTERN);
    360    }
    361
    362    /*
    363     * (non-Javadoc)
    364     *
    365     * @see java.io.InputStream#read(byte[], int, int)
    366     */
    367    @Override
    368    public int read(final byte[] b, final int off, final int len) throws IOException {
    369        if (len == 0) {
    370            return 0;
    371        }
    372        if (currentEntry == null) {
    373            throw new IllegalStateException("No current ar entry");
    374        }
    375        final long entryEnd = entryOffset + currentEntry.getLength();
    376        if (len < 0 || offset >= entryEnd) {
    377            return -1;
    378        }
    379        final int toRead = (int) Math.min(len, entryEnd - offset);
    380        final int ret = this.input.read(b, off, toRead);
    381        trackReadBytes(ret);
    382        return ret;
    383    }
    384
    385    /**
    386     * Reads the GNU archive String Table.
    387     *
    388     * @see #isGNUStringTable
    389     */
    390    private ArArchiveEntry readGNUStringTable(final byte[] length, final int offset, final int len) throws IOException {
    391        final int bufflen = asInt(length, offset, len); // Assume length will fit in an int
    392        namebuffer = IOUtils.readRange(input, bufflen);
    393        final int read = namebuffer.length;
    394        trackReadBytes(read);
    395        if (read != bufflen){
    396            throw new IOException("Failed to read complete // record: expected="
    397                                  + bufflen + " read=" + read);
    398        }
    399        return new ArArchiveEntry(GNU_STRING_TABLE_NAME, bufflen);
    400    }
    401
    402    private void trackReadBytes(final long read) {
    403        count(read);
    404        if (read > 0) {
    405            offset += read;
    406        }
    407    }
    408}