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.compressors.zstandard;
020
021import org.apache.commons.compress.utils.OsgiUtils;
022
023/**
024 * Utility code for the Zstandard compression format.
025 *
026 * @ThreadSafe
027 * @since 1.16
028 */
029public class ZstdUtils {
030
031    enum CachedAvailability {
032        DONT_CACHE, CACHED_AVAILABLE, CACHED_UNAVAILABLE
033    }
034
035    /**
036     * Zstandard Frame Magic Bytes.
037     */
038    private static final byte[] ZSTANDARD_FRAME_MAGIC = { (byte) 0x28, (byte) 0xB5, (byte) 0x2F, (byte) 0xFD };
039
040    /**
041     * Skippable Frame Magic Bytes - the three common bytes.
042     */
043    private static final byte[] SKIPPABLE_FRAME_MAGIC = { (byte) 0x2A, (byte) 0x4D, (byte) 0x18 };
044
045    private static volatile CachedAvailability cachedZstdAvailability;
046
047    static {
048        cachedZstdAvailability = CachedAvailability.DONT_CACHE;
049        setCacheZstdAvailablity(!OsgiUtils.isRunningInOsgiEnvironment());
050    }
051
052    // only exists to support unit tests
053    static CachedAvailability getCachedZstdAvailability() {
054        return cachedZstdAvailability;
055    }
056
057    private static boolean internalIsZstdCompressionAvailable() {
058        try {
059            Class.forName("com.github.luben.zstd.ZstdInputStream");
060            return true;
061        } catch (final NoClassDefFoundError | Exception error) { // NOSONAR
062            return false;
063        }
064    }
065
066    /**
067     * Are the classes required to support Zstandard compression available?
068     *
069     * @return true if the classes required to support Zstandard compression are available
070     */
071    public static boolean isZstdCompressionAvailable() {
072        final CachedAvailability cachedResult = cachedZstdAvailability;
073        if (cachedResult != CachedAvailability.DONT_CACHE) {
074            return cachedResult == CachedAvailability.CACHED_AVAILABLE;
075        }
076        return internalIsZstdCompressionAvailable();
077    }
078
079    /**
080     * Checks if the signature matches what is expected for a Zstandard file.
081     *
082     * @param signature the bytes to check
083     * @param length    the number of bytes to check
084     * @return true if signature matches the Ztstandard or skippable frame magic bytes, false otherwise
085     */
086    public static boolean matches(final byte[] signature, final int length) {
087        if (length < ZSTANDARD_FRAME_MAGIC.length) {
088            return false;
089        }
090
091        boolean isZstandard = true;
092        for (int i = 0; i < ZSTANDARD_FRAME_MAGIC.length; ++i) {
093            if (signature[i] != ZSTANDARD_FRAME_MAGIC[i]) {
094                isZstandard = false;
095                break;
096            }
097        }
098        if (isZstandard) {
099            return true;
100        }
101
102        if (0x50 == (signature[0] & 0xF0)) {
103            // skippable frame
104            for (int i = 0; i < SKIPPABLE_FRAME_MAGIC.length; ++i) {
105                if (signature[i + 1] != SKIPPABLE_FRAME_MAGIC[i]) {
106                    return false;
107                }
108            }
109
110            return true;
111        }
112
113        return false;
114    }
115
116    /**
117     * Whether to cache the result of the Zstandard for Java check.
118     *
119     * <p>
120     * This defaults to {@code false} in an OSGi environment and {@code true} otherwise.
121     * </p>
122     *
123     * @param doCache whether to cache the result
124     */
125    public static void setCacheZstdAvailablity(final boolean doCache) {
126        if (!doCache) {
127            cachedZstdAvailability = CachedAvailability.DONT_CACHE;
128        } else if (cachedZstdAvailability == CachedAvailability.DONT_CACHE) {
129            final boolean hasZstd = internalIsZstdCompressionAvailable();
130            cachedZstdAvailability = hasZstd ? CachedAvailability.CACHED_AVAILABLE : CachedAvailability.CACHED_UNAVAILABLE;
131        }
132    }
133
134    /** Private constructor to prevent instantiation of this utility class. */
135    private ZstdUtils() {
136    }
137}