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
020import java.io.IOException;
021import java.math.BigInteger;
022import java.util.Calendar;
023import java.util.Date;
024import java.util.zip.CRC32;
025import java.util.zip.ZipEntry;
026
027/**
028 * Utility class for handling DOS and Java time conversions.
029 * @Immutable
030 */
031public abstract class ZipUtil {
032    /**
033     * Smallest date/time ZIP can handle.
034     */
035    private static final byte[] DOS_TIME_MIN = ZipLong.getBytes(0x00002100L);
036
037    /**
038     * Convert a Date object to a DOS date/time field.
039     * @param time the <code>Date</code> to convert
040     * @return the date as a <code>ZipLong</code>
041     */
042    public static ZipLong toDosTime(Date time) {
043        return new ZipLong(toDosTime(time.getTime()));
044    }
045
046    /**
047     * Convert a Date object to a DOS date/time field.
048     *
049     * <p>Stolen from InfoZip's <code>fileio.c</code></p>
050     * @param t number of milliseconds since the epoch
051     * @return the date as a byte array
052     */
053    public static byte[] toDosTime(long t) {
054        byte[] result = new byte[4];
055        toDosTime(t, result, 0);
056        return result;
057    }
058
059    /**
060     * Convert a Date object to a DOS date/time field.
061     *
062     * <p>Stolen from InfoZip's <code>fileio.c</code></p>
063     * @param t number of milliseconds since the epoch
064     * @param buf the output buffer
065     * @param offset
066     *         The offset within the output buffer of the first byte to be written.
067     *         must be non-negative and no larger than <tt>buf.length-4</tt>
068     */
069    public static void toDosTime(long t, byte[] buf, int offset) {
070        toDosTime(Calendar.getInstance(), t, buf, offset);
071    }
072
073    static void toDosTime(Calendar c, long t, byte[] buf, int offset) {
074        c.setTimeInMillis(t);
075
076        int year = c.get(Calendar.YEAR);
077        if (year < 1980) {
078            System.arraycopy(DOS_TIME_MIN, 0, buf, offset, DOS_TIME_MIN.length);// stop callers from changing the array
079            return;
080        }
081        int month = c.get(Calendar.MONTH) + 1;
082        long value =  ((year - 1980) << 25)
083                |         (month << 21)
084                |         (c.get(Calendar.DAY_OF_MONTH) << 16)
085                |         (c.get(Calendar.HOUR_OF_DAY) << 11)
086                |         (c.get(Calendar.MINUTE) << 5)
087                |         (c.get(Calendar.SECOND) >> 1);
088        ZipLong.putLong(value, buf, offset);
089    }
090
091
092    /**
093     * Assumes a negative integer really is a positive integer that
094     * has wrapped around and re-creates the original value.
095     *
096     * @param i the value to treat as unsigned int.
097     * @return the unsigned int as a long.
098     */
099    public static long adjustToLong(int i) {
100        if (i < 0) {
101            return 2 * ((long) Integer.MAX_VALUE) + 2 + i;
102        } else {
103            return i;
104        }
105    }
106
107    /**
108     * Reverses a byte[] array.  Reverses in-place (thus provided array is
109     * mutated), but also returns same for convenience.
110     *
111     * @param array to reverse (mutated in-place, but also returned for
112     *        convenience).
113     *
114     * @return the reversed array (mutated in-place, but also returned for
115     *        convenience).
116     * @since 1.5
117     */
118    public static byte[] reverse(final byte[] array) {
119        final int z = array.length - 1; // position of last element
120        for (int i = 0; i < array.length / 2; i++) {
121            byte x = array[i];
122            array[i] = array[z - i];
123            array[z - i] = x;
124        }
125        return array;
126    }
127
128    /**
129     * Converts a BigInteger into a long, and blows up
130     * (NumberFormatException) if the BigInteger is too big.
131     *
132     * @param big BigInteger to convert.
133     * @return long representation of the BigInteger.
134     */
135    static long bigToLong(BigInteger big) {
136        if (big.bitLength() <= 63) { // bitLength() doesn't count the sign bit.
137            return big.longValue();
138        } else {
139            throw new NumberFormatException("The BigInteger cannot fit inside a 64 bit java long: [" + big + "]");
140        }
141    }
142
143    /**
144     * <p>
145     * Converts a long into a BigInteger.  Negative numbers between -1 and
146     * -2^31 are treated as unsigned 32 bit (e.g., positive) integers.
147     * Negative numbers below -2^31 cause an IllegalArgumentException
148     * to be thrown.
149     * </p>
150     *
151     * @param l long to convert to BigInteger.
152     * @return BigInteger representation of the provided long.
153     */
154    static BigInteger longToBig(long l) {
155        if (l < Integer.MIN_VALUE) {
156            throw new IllegalArgumentException("Negative longs < -2^31 not permitted: [" + l + "]");
157        } else if (l < 0 && l >= Integer.MIN_VALUE) {
158            // If someone passes in a -2, they probably mean 4294967294
159            // (For example, Unix UID/GID's are 32 bit unsigned.)
160            l = ZipUtil.adjustToLong((int) l);
161        }
162        return BigInteger.valueOf(l);
163    }
164
165    /**
166     * Converts a signed byte into an unsigned integer representation
167     * (e.g., -1 becomes 255).
168     *
169     * @param b byte to convert to int
170     * @return int representation of the provided byte
171     * @since 1.5
172     */
173    public static int signedByteToUnsignedInt(byte b) {
174        if (b >= 0) {
175            return b;
176        } else {
177            return 256 + b;
178        }
179    }
180
181    /**
182     * Converts an unsigned integer to a signed byte (e.g., 255 becomes -1).
183     *
184     * @param i integer to convert to byte
185     * @return byte representation of the provided int
186     * @throws IllegalArgumentException if the provided integer is not inside the range [0,255].
187     * @since 1.5
188     */
189    public static byte unsignedIntToSignedByte(int i) {
190        if (i > 255 || i < 0) {
191            throw new IllegalArgumentException("Can only convert non-negative integers between [0,255] to byte: [" + i + "]");
192        }
193        if (i < 128) {
194            return (byte) i;
195        } else {
196            return (byte) (i - 256);
197        }
198    }
199
200    /**
201     * Convert a DOS date/time field to a Date object.
202     *
203     * @param zipDosTime contains the stored DOS time.
204     * @return a Date instance corresponding to the given time.
205     */
206    public static Date fromDosTime(ZipLong zipDosTime) {
207        long dosTime = zipDosTime.getValue();
208        return new Date(dosToJavaTime(dosTime));
209    }
210
211    /**
212     * Converts DOS time to Java time (number of milliseconds since
213     * epoch).
214     * @param dosTime time to convert
215     * @return converted time
216     */
217    public static long dosToJavaTime(long dosTime) {
218        Calendar cal = Calendar.getInstance();
219        // CheckStyle:MagicNumberCheck OFF - no point
220        cal.set(Calendar.YEAR, (int) ((dosTime >> 25) & 0x7f) + 1980);
221        cal.set(Calendar.MONTH, (int) ((dosTime >> 21) & 0x0f) - 1);
222        cal.set(Calendar.DATE, (int) (dosTime >> 16) & 0x1f);
223        cal.set(Calendar.HOUR_OF_DAY, (int) (dosTime >> 11) & 0x1f);
224        cal.set(Calendar.MINUTE, (int) (dosTime >> 5) & 0x3f);
225        cal.set(Calendar.SECOND, (int) (dosTime << 1) & 0x3e);
226        cal.set(Calendar.MILLISECOND, 0);
227        // CheckStyle:MagicNumberCheck ON
228        return cal.getTime().getTime();
229    }
230
231    /**
232     * If the entry has Unicode*ExtraFields and the CRCs of the
233     * names/comments match those of the extra fields, transfer the
234     * known Unicode values from the extra field.
235     */
236    static void setNameAndCommentFromExtraFields(ZipArchiveEntry ze,
237                                                 byte[] originalNameBytes,
238                                                 byte[] commentBytes) {
239        UnicodePathExtraField name = (UnicodePathExtraField)
240            ze.getExtraField(UnicodePathExtraField.UPATH_ID);
241        String originalName = ze.getName();
242        String newName = getUnicodeStringIfOriginalMatches(name,
243                                                           originalNameBytes);
244        if (newName != null && !originalName.equals(newName)) {
245            ze.setName(newName);
246        }
247
248        if (commentBytes != null && commentBytes.length > 0) {
249            UnicodeCommentExtraField cmt = (UnicodeCommentExtraField)
250                ze.getExtraField(UnicodeCommentExtraField.UCOM_ID);
251            String newComment =
252                getUnicodeStringIfOriginalMatches(cmt, commentBytes);
253            if (newComment != null) {
254                ze.setComment(newComment);
255            }
256        }
257    }
258
259    /**
260     * If the stored CRC matches the one of the given name, return the
261     * Unicode name of the given field.
262     *
263     * <p>If the field is null or the CRCs don't match, return null
264     * instead.</p>
265     */
266    private static 
267        String getUnicodeStringIfOriginalMatches(AbstractUnicodeExtraField f,
268                                                 byte[] orig) {
269        if (f != null) {
270            CRC32 crc32 = new CRC32();
271            crc32.update(orig);
272            long origCRC32 = crc32.getValue();
273
274            if (origCRC32 == f.getNameCRC32()) {
275                try {
276                    return ZipEncodingHelper
277                        .UTF8_ZIP_ENCODING.decode(f.getUnicodeName());
278                } catch (IOException ex) {
279                    // UTF-8 unsupported?  should be impossible the
280                    // Unicode*ExtraField must contain some bad bytes
281
282                    // TODO log this anywhere?
283                    return null;
284                }
285            }
286        }
287        return null;
288    }
289
290    /**
291     * Create a copy of the given array - or return null if the
292     * argument is null.
293     */
294    static byte[] copy(byte[] from) {
295        if (from != null) {
296            byte[] to = new byte[from.length];
297            System.arraycopy(from, 0, to, 0, to.length);
298            return to;
299        }
300        return null;
301    }
302    static void copy(byte[] from, byte[] to, int offset) {
303        if (from != null) {
304            System.arraycopy(from, 0, to, offset, from.length);
305        }
306    }
307
308
309    /**
310     * Whether this library is able to read or write the given entry.
311     */
312    static boolean canHandleEntryData(ZipArchiveEntry entry) {
313        return supportsEncryptionOf(entry) && supportsMethodOf(entry);
314    }
315
316    /**
317     * Whether this library supports the encryption used by the given
318     * entry.
319     *
320     * @return true if the entry isn't encrypted at all
321     */
322    private static boolean supportsEncryptionOf(ZipArchiveEntry entry) {
323        return !entry.getGeneralPurposeBit().usesEncryption();
324    }
325
326    /**
327     * Whether this library supports the compression method used by
328     * the given entry.
329     *
330     * @return true if the compression method is STORED or DEFLATED
331     */
332    private static boolean supportsMethodOf(ZipArchiveEntry entry) {
333        return entry.getMethod() == ZipEntry.STORED
334            || entry.getMethod() == ZipMethod.UNSHRINKING.getCode()
335            || entry.getMethod() == ZipMethod.IMPLODING.getCode()
336            || entry.getMethod() == ZipEntry.DEFLATED;
337    }
338
339    /**
340     * Checks whether the entry requires features not (yet) supported
341     * by the library and throws an exception if it does.
342     */
343    static void checkRequestedFeatures(ZipArchiveEntry ze)
344        throws UnsupportedZipFeatureException {
345        if (!supportsEncryptionOf(ze)) {
346            throw
347                new UnsupportedZipFeatureException(UnsupportedZipFeatureException
348                                                   .Feature.ENCRYPTION, ze);
349        }
350        if (!supportsMethodOf(ze)) {
351            ZipMethod m = ZipMethod.getMethodByCode(ze.getMethod());
352            if (m == null) {
353                throw
354                    new UnsupportedZipFeatureException(UnsupportedZipFeatureException
355                                                       .Feature.METHOD, ze);
356            } else {
357                throw new UnsupportedZipFeatureException(m, ze);
358            }
359        }
360    }
361}