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        return length >= 8 && signature[0] == 0x21 &&
275                signature[1] == 0x3c && signature[2] == 0x61 &&
276                signature[3] == 0x72 && signature[4] == 0x63 &&
277                signature[5] == 0x68 && signature[6] == 0x3e &&
278                signature[7] == 0x0a;
279    }
280
281    static final String BSD_LONGNAME_PREFIX = "#1/";
282    private static final int BSD_LONGNAME_PREFIX_LEN =
283        BSD_LONGNAME_PREFIX.length();
284    private static final String BSD_LONGNAME_PATTERN =
285        "^" + BSD_LONGNAME_PREFIX + "\\d+";
286
287    /**
288     * Does the name look like it is a long name (or a name containing
289     * spaces) as encoded by BSD ar?
290     *
291     * <p>From the FreeBSD ar(5) man page:</p>
292     * <pre>
293     * BSD   In the BSD variant, names that are shorter than 16
294     *       characters and without embedded spaces are stored
295     *       directly in this field.  If a name has an embedded
296     *       space, or if it is longer than 16 characters, then
297     *       the string "#1/" followed by the decimal represen-
298     *       tation of the length of the file name is placed in
299     *       this field. The actual file name is stored immedi-
300     *       ately after the archive header.  The content of the
301     *       archive member follows the file name.  The ar_size
302     *       field of the header (see below) will then hold the
303     *       sum of the size of the file name and the size of
304     *       the member.
305     * </pre>
306     *
307     * @since 1.3
308     */
309    private static boolean isBSDLongName(final String name) {
310        return name != null && name.matches(BSD_LONGNAME_PATTERN);
311    }
312
313    /**
314     * Reads the real name from the current stream assuming the very
315     * first bytes to be read are the real file name.
316     *
317     * @see #isBSDLongName
318     *
319     * @since 1.3
320     */
321    private String getBSDLongName(final String bsdLongName) throws IOException {
322        final int nameLen =
323            Integer.parseInt(bsdLongName.substring(BSD_LONGNAME_PREFIX_LEN));
324        final byte[] name = new byte[nameLen];
325        final int read = IOUtils.readFully(this, name);
326        if (read != nameLen) {
327            throw new EOFException();
328        }
329        return ArchiveUtils.toAsciiString(name);
330    }
331
332    private static final String GNU_STRING_TABLE_NAME = "//";
333
334    /**
335     * Is this the name of the "Archive String Table" as used by
336     * SVR4/GNU to store long file names?
337     *
338     * <p>GNU ar stores multiple extended filenames in the data section
339     * of a file with the name "//", this record is referred to by
340     * future headers.</p>
341     *
342     * <p>A header references an extended filename by storing a "/"
343     * followed by a decimal offset to the start of the filename in
344     * the extended filename data section.</p>
345     *
346     * <p>The format of the "//" file itself is simply a list of the
347     * long filenames, each separated by one or more LF
348     * characters. Note that the decimal offsets are number of
349     * characters, not line or string number within the "//" file.</p>
350     */
351    private static boolean isGNUStringTable(final String name) {
352        return GNU_STRING_TABLE_NAME.equals(name);
353    }
354
355    /**
356     * Reads the GNU archive String Table.
357     *
358     * @see #isGNUStringTable
359     */
360    private ArArchiveEntry readGNUStringTable(final byte[] length) throws IOException {
361        final int bufflen = asInt(length); // Assume length will fit in an int
362        namebuffer = new byte[bufflen];
363        final int read = IOUtils.readFully(this, namebuffer, 0, bufflen);
364        if (read != bufflen){
365            throw new IOException("Failed to read complete // record: expected="
366                                  + bufflen + " read=" + read);
367        }
368        return new ArArchiveEntry(GNU_STRING_TABLE_NAME, bufflen);
369    }
370
371    private static final String GNU_LONGNAME_PATTERN = "^/\\d+";
372
373    /**
374     * Does the name look like it is a long name (or a name containing
375     * spaces) as encoded by SVR4/GNU ar?
376     *
377     * @see #isGNUStringTable
378     */
379    private boolean isGNULongName(final String name) {
380        return name != null && name.matches(GNU_LONGNAME_PATTERN);
381    }
382}