    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.io.filefilter;
    018
    019import java.io.File;
    020import java.io.IOException;
    021import java.io.RandomAccessFile;
    022import java.io.Serializable;
    023import java.nio.ByteBuffer;
    024import java.nio.channels.FileChannel;
    025import java.nio.charset.Charset;
    026import java.nio.file.FileVisitResult;
    027import java.nio.file.Files;
    028import java.nio.file.Path;
    029import java.nio.file.attribute.BasicFileAttributes;
    030import java.util.Arrays;
    031import java.util.Objects;
    032
    033import org.apache.commons.io.IOUtils;
    034import org.apache.commons.io.RandomAccessFileMode;
    035
    036/**
    037 * <p>
    038 * File filter for matching files containing a "magic number". A magic number
    039 * is a unique series of bytes common to all files of a specific file format.
    040 * For instance, all Java class files begin with the bytes
    041 * {@code 0xCAFEBABE}.
    042 * </p>
    043 * <h2>Using Classic IO</h2>
    044 * <pre>
    045 * File dir = FileUtils.current();
    046 * MagicNumberFileFilter javaClassFileFilter =
    047 *     MagicNumberFileFilter(new byte[] {(byte) 0xCA, (byte) 0xFE,
    048 *       (byte) 0xBA, (byte) 0xBE});
    049 * String[] javaClassFiles = dir.list(javaClassFileFilter);
    050 * for (String javaClassFile : javaClassFiles) {
    051 *     System.out.println(javaClassFile);
    052 * }
    053 * </pre>
    054 *
    055 * <p>
    056 * Sometimes, such as in the case of TAR files, the
    057 * magic number will be offset by a certain number of bytes in the file. In the
    058 * case of TAR archive files, this offset is 257 bytes.
    059 * </p>
    060 *
    061 * <pre>
    062 * File dir = FileUtils.current();
    063 * MagicNumberFileFilter tarFileFilter =
    064 *     MagicNumberFileFilter("ustar", 257);
    065 * String[] tarFiles = dir.list(tarFileFilter);
    066 * for (String tarFile : tarFiles) {
    067 *     System.out.println(tarFile);
    068 * }
    069 * </pre>
    070 * <h2>Using NIO</h2>
    071 * <pre>
    072 * final Path dir = PathUtils.current();
    073 * final AccumulatorPathVisitor visitor = AccumulatorPathVisitor.withLongCounters(MagicNumberFileFilter("ustar", 257));
    074 * //
    075 * // Walk one dir
    076 * Files.<b>walkFileTree</b>(dir, Collections.emptySet(), 1, visitor);
    077 * System.out.println(visitor.getPathCounters());
    078 * System.out.println(visitor.getFileList());
    079 * //
    080 * visitor.getPathCounters().reset();
    081 * //
    082 * // Walk dir tree
    083 * Files.<b>walkFileTree</b>(dir, visitor);
    084 * System.out.println(visitor.getPathCounters());
    085 * System.out.println(visitor.getDirList());
    086 * System.out.println(visitor.getFileList());
    087 * </pre>
    088 * <h2>Deprecating Serialization</h2>
    089 * <p>
    090 * <em>Serialization is deprecated and will be removed in 3.0.</em>
    091 * </p>
    092 *
    093 * @since 2.0
    094 * @see FileFilterUtils#magicNumberFileFilter(byte[])
    095 * @see FileFilterUtils#magicNumberFileFilter(String)
    096 * @see FileFilterUtils#magicNumberFileFilter(byte[], long)
    097 * @see FileFilterUtils#magicNumberFileFilter(String, long)
    098 */
    099public class MagicNumberFileFilter extends AbstractFileFilter implements
    100        Serializable {
    101
    102    /**
    103     * The serialization version unique identifier.
    104     */
    105    private static final long serialVersionUID = -547733176983104172L;
    106
    107    /**
    108     * The magic number to compare against the file's bytes at the provided
    109     * offset.
    110     */
    111    private final byte[] magicNumbers;
    112
    113    /**
    114     * The offset (in bytes) within the files that the magic number's bytes
    115     * should appear.
    116     */
    117    private final long byteOffset;
    118
    119    /**
    120     * <p>
    121     * Constructs a new MagicNumberFileFilter and associates it with the magic
    122     * number to test for in files. This constructor assumes a starting offset
    123     * of {@code 0}.
    124     * </p>
    125     *
    126     * <p>
    127     * It is important to note that <em>the array is not cloned</em> and that
    128     * any changes to the magic number array after construction will affect the
    129     * behavior of this file filter.
    130     * </p>
    131     *
    132     * <pre>
    133     * MagicNumberFileFilter javaClassFileFilter =
    134     *     MagicNumberFileFilter(new byte[] {(byte) 0xCA, (byte) 0xFE,
    135     *       (byte) 0xBA, (byte) 0xBE});
    136     * </pre>
    137     *
    138     * @param magicNumber the magic number to look for in the file.
    139     *
    140     * @throws IllegalArgumentException if {@code magicNumber} is
    141     *         {@code null}, or contains no bytes.
    142     */
    143    public MagicNumberFileFilter(final byte[] magicNumber) {
    144        this(magicNumber, 0);
    145    }
    146
    147    /**
    148     * <p>
    149     * Constructs a new MagicNumberFileFilter and associates it with the magic
    150     * number to test for in files and the byte offset location in the file to
    151     * to look for that magic number.
    152     * </p>
    153     *
    154     * <pre>
    155     * MagicNumberFileFilter tarFileFilter =
    156     *     MagicNumberFileFilter(new byte[] {0x75, 0x73, 0x74, 0x61, 0x72}, 257);
    157     * </pre>
    158     *
    159     * <pre>
    160     * MagicNumberFileFilter javaClassFileFilter =
    161     *     MagicNumberFileFilter(new byte[] {0xCA, 0xFE, 0xBA, 0xBE}, 0);
    162     * </pre>
    163     *
    164     * @param magicNumbers the magic number to look for in the file.
    165     * @param offset the byte offset in the file to start comparing bytes.
    166     *
    167     * @throws IllegalArgumentException if {@code magicNumber}
    168     *         contains no bytes, or {@code offset}
    169     *         is a negative number.
    170     */
    171    public MagicNumberFileFilter(final byte[] magicNumbers, final long offset) {
    172        Objects.requireNonNull(magicNumbers, "magicNumbers");
    173        if (magicNumbers.length == 0) {
    174            throw new IllegalArgumentException("The magic number must contain at least one byte");
    175        }
    176        if (offset < 0) {
    177            throw new IllegalArgumentException("The offset cannot be negative");
    178        }
    179
    180        this.magicNumbers = magicNumbers.clone();
    181        this.byteOffset = offset;
    182    }
    183
    184    /**
    185     * <p>
    186     * Constructs a new MagicNumberFileFilter and associates it with the magic
    187     * number to test for in files. This constructor assumes a starting offset
    188     * of {@code 0}.
    189     * </p>
    190     *
    191     * Example usage:
    192     * <pre>
    193     * {@code
    194     * MagicNumberFileFilter xmlFileFilter =
    195     *     MagicNumberFileFilter("<?xml");
    196     * }
    197     * </pre>
    198     *
    199     * @param magicNumber the magic number to look for in the file.
    200     *        The string is converted to bytes using the platform default charset.
    201     *
    202     * @throws IllegalArgumentException if {@code magicNumber} is
    203     *         {@code null} or the empty String.
    204     */
    205    public MagicNumberFileFilter(final String magicNumber) {
    206        this(magicNumber, 0);
    207    }
    208
    209    /**
    210     * <p>
    211     * Constructs a new MagicNumberFileFilter and associates it with the magic
    212     * number to test for in files and the byte offset location in the file to
    213     * to look for that magic number.
    214     * </p>
    215     *
    216     * <pre>
    217     * MagicNumberFileFilter tarFileFilter =
    218     *     MagicNumberFileFilter("ustar", 257);
    219     * </pre>
    220     *
    221     * @param magicNumber the magic number to look for in the file.
    222     *        The string is converted to bytes using the platform default charset.
    223     * @param offset the byte offset in the file to start comparing bytes.
    224     *
    225     * @throws IllegalArgumentException if {@code magicNumber} is
    226     *         the empty String, or {@code offset} is
    227     *         a negative number.
    228     */
    229    public MagicNumberFileFilter(final String magicNumber, final long offset) {
    230        Objects.requireNonNull(magicNumber, "magicNumber");
    231        if (magicNumber.isEmpty()) {
    232            throw new IllegalArgumentException("The magic number must contain at least one byte");
    233        }
    234        if (offset < 0) {
    235            throw new IllegalArgumentException("The offset cannot be negative");
    236        }
    237
    238        this.magicNumbers = magicNumber.getBytes(Charset.defaultCharset()); // explicitly uses the platform default charset
    239        this.byteOffset = offset;
    240    }
    241
    242    /**
    243     * <p>
    244     * Accepts the provided file if the file contains the file filter's magic
    245     * number at the specified offset.
    246     * </p>
    247     *
    248     * <p>
    249     * If any {@link IOException}s occur while reading the file, the file will
    250     * be rejected.
    251     * </p>
    252     *
    253     * @param file the file to accept or reject.
    254     *
    255     * @return {@code true} if the file contains the filter's magic number
    256     *         at the specified offset, {@code false} otherwise.
    257     */
    258    @Override
    259    public boolean accept(final File file) {
    260        if (file != null && file.isFile() && file.canRead()) {
    261            try {
    262                try (RandomAccessFile randomAccessFile = RandomAccessFileMode.READ_ONLY.create(file)) {
    263                    final byte[] fileBytes = IOUtils.byteArray(this.magicNumbers.length);
    264                    randomAccessFile.seek(byteOffset);
    265                    final int read = randomAccessFile.read(fileBytes);
    266                    if (read != magicNumbers.length) {
    267                        return false;
    268                    }
    269                    return Arrays.equals(this.magicNumbers, fileBytes);
    270                }
    271            }
    272            catch (final IOException ignored) {
    273                // Do nothing, fall through and do not accept file
    274            }
    275        }
    276
    277        return false;
    278    }
    279
    280    /**
    281     * <p>
    282     * Accepts the provided file if the file contains the file filter's magic
    283     * number at the specified offset.
    284     * </p>
    285     *
    286     * <p>
    287     * If any {@link IOException}s occur while reading the file, the file will
    288     * be rejected.
    289     * </p>
    290     * @param file the file to accept or reject.
    291     *
    292     * @return {@code true} if the file contains the filter's magic number
    293     *         at the specified offset, {@code false} otherwise.
    294     * @since 2.9.0
    295     */
    296    @Override
    297    public FileVisitResult accept(final Path file, final BasicFileAttributes attributes) {
    298        if (file != null && Files.isRegularFile(file) && Files.isReadable(file)) {
    299            try {
    300                try (FileChannel fileChannel = FileChannel.open(file)) {
    301                    final ByteBuffer byteBuffer = ByteBuffer.allocate(this.magicNumbers.length);
    302                    final int read = fileChannel.read(byteBuffer);
    303                    if (read != magicNumbers.length) {
    304                        return FileVisitResult.TERMINATE;
    305                    }
    306                    return toFileVisitResult(Arrays.equals(this.magicNumbers, byteBuffer.array()));
    307                }
    308            }
    309            catch (final IOException ignored) {
    310                // Do nothing, fall through and do not accept file
    311            }
    312        }
    313        return FileVisitResult.TERMINATE;
    314    }
    315
    316    /**
    317     * Returns a String representation of the file filter, which includes the
    318     * magic number bytes and byte offset.
    319     *
    320     * @return a String representation of the file filter.
    321     */
    322    @Override
    323    public String toString() {
    324        final StringBuilder builder = new StringBuilder(super.toString());
    325        builder.append("(");
    326        builder.append(new String(magicNumbers, Charset.defaultCharset()));// TODO perhaps use hex if value is not
    327                                                                           // printable
    328        builder.append(",");
    329        builder.append(this.byteOffset);
    330        builder.append(")");
    331        return builder.toString();
    332    }
    333}