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 *
017 */
018package org.apache.commons.compress.archivers.zip;
019
020/**
021 * Parser/encoder for the "general purpose bit" field in ZIP's local
022 * file and central directory headers.
023 * 
024 * @since 1.1
025 * @NotThreadSafe
026 */
027public final class GeneralPurposeBit implements Cloneable {
028
029    /**
030     * Indicates that the file is encrypted.
031     */
032    private static final int ENCRYPTION_FLAG = 1 << 0;
033
034    /**
035     * Indicates the size of the sliding dictionary used by the compression method 6 (imploding).
036     * <ul>
037     *   <li>0: 4096 bytes</li>
038     *   <li>1: 8192 bytes</li>
039     * </ul>
040     */
041    private static final int SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1;
042
043    /**
044     * Indicates the number of Shannon-Fano trees used by the compression method 6 (imploding).
045     * <ul>
046     *   <li>0: 2 trees (lengths, distances)</li>
047     *   <li>1: 3 trees (literals, lengths, distances)</li>
048     * </ul>
049     */
050    private static final int NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2;
051
052    /**
053     * Indicates that a data descriptor stored after the file contents
054     * will hold CRC and size information.
055     */
056    private static final int DATA_DESCRIPTOR_FLAG = 1 << 3;
057
058    /**
059     * Indicates strong encryption.
060     */
061    private static final int STRONG_ENCRYPTION_FLAG = 1 << 6;
062
063    /**
064     * Indicates that filenames are written in UTF-8.
065     *
066     * <p>The only reason this is public is that {@link
067     * ZipArchiveOutputStream#EFS_FLAG} was public in Apache Commons
068     * Compress 1.0 and we needed a substitute for it.</p>
069     */
070    public static final int UFT8_NAMES_FLAG = 1 << 11;
071
072    private boolean languageEncodingFlag = false;
073    private boolean dataDescriptorFlag = false;
074    private boolean encryptionFlag = false;
075    private boolean strongEncryptionFlag = false;
076    private int slidingDictionarySize;
077    private int numberOfShannonFanoTrees;
078
079    public GeneralPurposeBit() {
080    }
081
082    /**
083     * whether the current entry uses UTF8 for file name and comment.
084     */
085    public boolean usesUTF8ForNames() {
086        return languageEncodingFlag;
087    }
088
089    /**
090     * whether the current entry will use UTF8 for file name and comment.
091     */
092    public void useUTF8ForNames(boolean b) {
093        languageEncodingFlag = b;
094    }
095
096    /**
097     * whether the current entry uses the data descriptor to store CRC
098     * and size information
099     */
100    public boolean usesDataDescriptor() {
101        return dataDescriptorFlag;
102    }
103
104    /**
105     * whether the current entry will use the data descriptor to store
106     * CRC and size information
107     */
108    public void useDataDescriptor(boolean b) {
109        dataDescriptorFlag = b;
110    }
111
112    /**
113     * whether the current entry is encrypted
114     */
115    public boolean usesEncryption() {
116        return encryptionFlag;
117    }
118
119    /**
120     * whether the current entry will be encrypted
121     */
122    public void useEncryption(boolean b) {
123        encryptionFlag = b;
124    }
125
126    /**
127     * whether the current entry is encrypted using strong encryption
128     */
129    public boolean usesStrongEncryption() {
130        return encryptionFlag && strongEncryptionFlag;
131    }
132
133    /**
134     * whether the current entry will be encrypted  using strong encryption
135     */
136    public void useStrongEncryption(boolean b) {
137        strongEncryptionFlag = b;
138        if (b) {
139            useEncryption(true);
140        }
141    }
142
143    /**
144     * Returns the sliding dictionary size used by the compression method 6 (imploding).
145     */
146    int getSlidingDictionarySize() {
147        return slidingDictionarySize;
148    }
149
150    /**
151     * Returns the number of trees used by the compression method 6 (imploding).
152     */
153    int getNumberOfShannonFanoTrees() {
154        return numberOfShannonFanoTrees;
155    }
156
157    /**
158     * Encodes the set bits in a form suitable for ZIP archives.
159     */
160    public byte[] encode() {
161        byte[] result = new byte[2];
162        encode(result, 0);
163        return result;
164    }
165
166
167    /**
168     * Encodes the set bits in a form suitable for ZIP archives.
169     *
170     * @param buf the output buffer
171     * @param  offset
172     *         The offset within the output buffer of the first byte to be written.
173     *         must be non-negative and no larger than <tt>buf.length-2</tt>
174     */
175    public void encode(byte[] buf, int offset) {
176                ZipShort.putShort((dataDescriptorFlag ? DATA_DESCRIPTOR_FLAG : 0)
177                        |
178                        (languageEncodingFlag ? UFT8_NAMES_FLAG : 0)
179                        |
180                        (encryptionFlag ? ENCRYPTION_FLAG : 0)
181                        |
182                        (strongEncryptionFlag ? STRONG_ENCRYPTION_FLAG : 0)
183                        , buf, offset);
184    }
185
186    /**
187     * Parses the supported flags from the given archive data.
188     * 
189     * @param data local file header or a central directory entry.
190     * @param offset offset at which the general purpose bit starts
191     */
192    public static GeneralPurposeBit parse(final byte[] data, final int offset) {
193        final int generalPurposeFlag = ZipShort.getValue(data, offset);
194        GeneralPurposeBit b = new GeneralPurposeBit();
195        b.useDataDescriptor((generalPurposeFlag & DATA_DESCRIPTOR_FLAG) != 0);
196        b.useUTF8ForNames((generalPurposeFlag & UFT8_NAMES_FLAG) != 0);
197        b.useStrongEncryption((generalPurposeFlag & STRONG_ENCRYPTION_FLAG) != 0);
198        b.useEncryption((generalPurposeFlag & ENCRYPTION_FLAG) != 0);
199        b.slidingDictionarySize = (generalPurposeFlag & SLIDING_DICTIONARY_SIZE_FLAG) != 0 ? 8192 : 4096;
200        b.numberOfShannonFanoTrees = (generalPurposeFlag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) != 0 ? 3 : 2;
201        return b;
202    }
203
204    @Override
205    public int hashCode() {
206        return 3 * (7 * (13 * (17 * (encryptionFlag ? 1 : 0)
207                               + (strongEncryptionFlag ? 1 : 0))
208                         + (languageEncodingFlag ? 1 : 0))
209                    + (dataDescriptorFlag ? 1 : 0));
210    }
211
212    @Override
213    public boolean equals(Object o) {
214        if (!(o instanceof GeneralPurposeBit)) {
215            return false;
216        }
217        GeneralPurposeBit g = (GeneralPurposeBit) o;
218        return g.encryptionFlag == encryptionFlag
219            && g.strongEncryptionFlag == strongEncryptionFlag
220            && g.languageEncodingFlag == languageEncodingFlag
221            && g.dataDescriptorFlag == dataDescriptorFlag;
222    }
223
224    @Override
225    public Object clone() {
226        try {
227            return super.clone();
228        } catch (CloneNotSupportedException ex) {
229            // impossible
230            throw new RuntimeException("GeneralPurposeBit is not Cloneable?", ex);
231        }
232    }
233}