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