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.util.ArrayList;
021import java.util.List;
022import java.util.Map;
023import java.util.Objects;
024import java.util.concurrent.ConcurrentHashMap;
025import java.util.zip.ZipException;
026
027/**
028 * ZipExtraField related methods
029 * @NotThreadSafe because the HashMap is not synch.
030 */
031// CheckStyle:HideUtilityClassConstructorCheck OFF (bc)
032public class ExtraFieldUtils {
033
034    private static final int WORD = 4;
035
036    /**
037     * Static registry of known extra fields.
038     */
039    private static final Map<ZipShort, Class<?>> implementations;
040
041    static {
042        implementations = new ConcurrentHashMap<>();
043        register(AsiExtraField.class);
044        register(X5455_ExtendedTimestamp.class);
045        register(X7875_NewUnix.class);
046        register(JarMarker.class);
047        register(UnicodePathExtraField.class);
048        register(UnicodeCommentExtraField.class);
049        register(Zip64ExtendedInformationExtraField.class);
050        register(X000A_NTFS.class);
051        register(X0014_X509Certificates.class);
052        register(X0015_CertificateIdForFile.class);
053        register(X0016_CertificateIdForCentralDirectory.class);
054        register(X0017_StrongEncryptionHeader.class);
055        register(X0019_EncryptionRecipientCertificateList.class);
056        register(ResourceAlignmentExtraField.class);
057    }
058
059    /**
060     * Register a ZipExtraField implementation.
061     *
062     * <p>The given class must have a no-arg constructor and implement
063     * the {@link ZipExtraField ZipExtraField interface}.</p>
064     * @param c the class to register
065     */
066    public static void register(final Class<?> c) {
067        try {
068            final ZipExtraField ze = (ZipExtraField) c.newInstance();
069            implementations.put(ze.getHeaderId(), c);
070        } catch (final ClassCastException cc) { // NOSONAR
071            throw new RuntimeException(c + " doesn\'t implement ZipExtraField"); //NOSONAR
072        } catch (final InstantiationException ie) { // NOSONAR
073            throw new RuntimeException(c + " is not a concrete class"); //NOSONAR
074        } catch (final IllegalAccessException ie) { // NOSONAR
075            throw new RuntimeException(c + "\'s no-arg constructor is not public"); //NOSONAR
076        }
077    }
078
079    /**
080     * Create an instance of the appropriate ExtraField, falls back to
081     * {@link UnrecognizedExtraField UnrecognizedExtraField}.
082     * @param headerId the header identifier
083     * @return an instance of the appropriate ExtraField
084     * @throws InstantiationException if unable to instantiate the class
085     * @throws IllegalAccessException if not allowed to instantiate the class
086     */
087    public static ZipExtraField createExtraField(final ZipShort headerId)
088        throws InstantiationException, IllegalAccessException {
089        ZipExtraField field = createExtraFieldNoDefault(headerId);
090        if (field != null) {
091            return field;
092        }
093        final UnrecognizedExtraField u = new UnrecognizedExtraField();
094        u.setHeaderId(headerId);
095        return u;
096    }
097
098    /**
099     * Create an instance of the appropriate ExtraField.
100     * @param headerId the header identifier
101     * @return an instance of the appropriate ExtraField or null if
102     * the id is not supported
103     * @throws InstantiationException if unable to instantiate the class
104     * @throws IllegalAccessException if not allowed to instantiate the class
105     * @since 1.19
106     */
107    public static ZipExtraField createExtraFieldNoDefault(final ZipShort headerId)
108        throws InstantiationException, IllegalAccessException {
109        final Class<?> c = implementations.get(headerId);
110        if (c != null) {
111            return (ZipExtraField) c.newInstance();
112        }
113        return null;
114    }
115
116    /**
117     * Split the array into ExtraFields and populate them with the
118     * given data as local file data, throwing an exception if the
119     * data cannot be parsed.
120     * @param data an array of bytes as it appears in local file data
121     * @return an array of ExtraFields
122     * @throws ZipException on error
123     */
124    public static ZipExtraField[] parse(final byte[] data) throws ZipException {
125        return parse(data, true, UnparseableExtraField.THROW);
126    }
127
128    /**
129     * Split the array into ExtraFields and populate them with the
130     * given data, throwing an exception if the data cannot be parsed.
131     * @param data an array of bytes
132     * @param local whether data originates from the local file data
133     * or the central directory
134     * @return an array of ExtraFields
135     * @throws ZipException on error
136     */
137    public static ZipExtraField[] parse(final byte[] data, final boolean local)
138        throws ZipException {
139        return parse(data, local, UnparseableExtraField.THROW);
140    }
141
142    /**
143     * Split the array into ExtraFields and populate them with the
144     * given data.
145     * @param data an array of bytes
146     * @param local whether data originates from the local file data
147     * or the central directory
148     * @param onUnparseableData what to do if the extra field data
149     * cannot be parsed.
150     * @return an array of ExtraFields
151     * @throws ZipException on error
152     *
153     * @since 1.1
154     */
155    public static ZipExtraField[] parse(final byte[] data, final boolean local,
156                                        final UnparseableExtraField onUnparseableData)
157        throws ZipException {
158        return parse(data, local, new ExtraFieldParsingBehavior() {
159            @Override
160            public ZipExtraField onUnparseableExtraField(byte[] data, int off, int len, boolean local,
161                int claimedLength) throws ZipException {
162                return onUnparseableData.onUnparseableExtraField(data, off, len, local, claimedLength);
163            }
164
165            @Override
166            public ZipExtraField createExtraField(final ZipShort headerId)
167                throws ZipException, InstantiationException, IllegalAccessException {
168                return ExtraFieldUtils.createExtraField(headerId);
169            }
170
171            @Override
172            public ZipExtraField fill(ZipExtraField field, byte[] data, int off, int len, boolean local)
173                throws ZipException {
174                return fillExtraField(field, data, off, len, local);
175            }
176        });
177    }
178
179    /**
180     * Split the array into ExtraFields and populate them with the
181     * given data.
182     * @param data an array of bytes
183     * @param parsingBehavior controls parsing of extra fields.
184     * @param local whether data originates from the local file data
185     * or the central directory
186     * @return an array of ExtraFields
187     * @throws ZipException on error
188     *
189     * @since 1.19
190     */
191    public static ZipExtraField[] parse(final byte[] data, final boolean local,
192                                        final ExtraFieldParsingBehavior parsingBehavior)
193        throws ZipException {
194        final List<ZipExtraField> v = new ArrayList<>();
195        int start = 0;
196        LOOP:
197        while (start <= data.length - WORD) {
198            final ZipShort headerId = new ZipShort(data, start);
199            final int length = new ZipShort(data, start + 2).getValue();
200            if (start + WORD + length > data.length) {
201                ZipExtraField field = parsingBehavior.onUnparseableExtraField(data, start, data.length - start,
202                    local, length);
203                if (field != null) {
204                    v.add(field);
205                }
206                // since we cannot parse the data we must assume
207                // the extra field consumes the whole rest of the
208                // available data
209                break LOOP;
210            }
211            try {
212                ZipExtraField ze = Objects.requireNonNull(parsingBehavior.createExtraField(headerId),
213                    "createExtraField must not return null");
214                v.add(Objects.requireNonNull(parsingBehavior.fill(ze, data, start + WORD, length, local),
215                    "fill must not return null"));
216                start += length + WORD;
217            } catch (final InstantiationException | IllegalAccessException ie) {
218                throw (ZipException) new ZipException(ie.getMessage()).initCause(ie);
219            }
220        }
221
222        final ZipExtraField[] result = new ZipExtraField[v.size()];
223        return v.toArray(result);
224    }
225
226    /**
227     * Merges the local file data fields of the given ZipExtraFields.
228     * @param data an array of ExtraFiles
229     * @return an array of bytes
230     */
231    public static byte[] mergeLocalFileDataData(final ZipExtraField[] data) {
232        final boolean lastIsUnparseableHolder = data.length > 0
233            && data[data.length - 1] instanceof UnparseableExtraFieldData;
234        final int regularExtraFieldCount =
235            lastIsUnparseableHolder ? data.length - 1 : data.length;
236
237        int sum = WORD * regularExtraFieldCount;
238        for (final ZipExtraField element : data) {
239            sum += element.getLocalFileDataLength().getValue();
240        }
241
242        final byte[] result = new byte[sum];
243        int start = 0;
244        for (int i = 0; i < regularExtraFieldCount; i++) {
245            System.arraycopy(data[i].getHeaderId().getBytes(),
246                             0, result, start, 2);
247            System.arraycopy(data[i].getLocalFileDataLength().getBytes(),
248                             0, result, start + 2, 2);
249            start += WORD;
250            final byte[] local = data[i].getLocalFileDataData();
251            if (local != null) {
252                System.arraycopy(local, 0, result, start, local.length);
253                start += local.length;
254            }
255        }
256        if (lastIsUnparseableHolder) {
257            final byte[] local = data[data.length - 1].getLocalFileDataData();
258            if (local != null) {
259                System.arraycopy(local, 0, result, start, local.length);
260            }
261        }
262        return result;
263    }
264
265    /**
266     * Merges the central directory fields of the given ZipExtraFields.
267     * @param data an array of ExtraFields
268     * @return an array of bytes
269     */
270    public static byte[] mergeCentralDirectoryData(final ZipExtraField[] data) {
271        final boolean lastIsUnparseableHolder = data.length > 0
272            && data[data.length - 1] instanceof UnparseableExtraFieldData;
273        final int regularExtraFieldCount =
274            lastIsUnparseableHolder ? data.length - 1 : data.length;
275
276        int sum = WORD * regularExtraFieldCount;
277        for (final ZipExtraField element : data) {
278            sum += element.getCentralDirectoryLength().getValue();
279        }
280        final byte[] result = new byte[sum];
281        int start = 0;
282        for (int i = 0; i < regularExtraFieldCount; i++) {
283            System.arraycopy(data[i].getHeaderId().getBytes(),
284                             0, result, start, 2);
285            System.arraycopy(data[i].getCentralDirectoryLength().getBytes(),
286                             0, result, start + 2, 2);
287            start += WORD;
288            final byte[] central = data[i].getCentralDirectoryData();
289            if (central != null) {
290                System.arraycopy(central, 0, result, start, central.length);
291                start += central.length;
292            }
293        }
294        if (lastIsUnparseableHolder) {
295            final byte[] central = data[data.length - 1].getCentralDirectoryData();
296            if (central != null) {
297                System.arraycopy(central, 0, result, start, central.length);
298            }
299        }
300        return result;
301    }
302
303    /**
304     * Fills in the extra field data into the given instance.
305     *
306     * <p>Calls {@link ZipExtraField#parseFromCentralDirectoryData} or {@link ZipExtraField#parseFromLocalFileData} internally and wraps any {@link ArrayIndexOutOfBoundsException} thrown into a {@link ZipException}.</p>
307     *
308     * @param ze the extra field instance to fill
309     * @param data the array of extra field data
310     * @param off offset into data where this field's data starts
311     * @param len the length of this field's data
312     * @param local whether the extra field data stems from the local
313     * file header. If this is false then the data is part if the
314     * central directory header extra data.
315     * @return the filled field, will never be {@code null}
316     * @throws ZipException if an error occurs
317     *
318     * @since 1.19
319     */
320    public static ZipExtraField fillExtraField(final ZipExtraField ze, final byte[] data, final int off,
321        final int len, final boolean local) throws ZipException {
322        try {
323            if (local) {
324                ze.parseFromLocalFileData(data, off, len);
325            } else {
326                ze.parseFromCentralDirectoryData(data, off, len);
327            }
328            return ze;
329        } catch (ArrayIndexOutOfBoundsException aiobe) {
330            throw (ZipException) new ZipException("Failed to parse corrupt ZIP extra field of type "
331                + Integer.toHexString(ze.getHeaderId().getValue())).initCause(aiobe);
332        }
333    }
334
335    /**
336     * "enum" for the possible actions to take if the extra field
337     * cannot be parsed.
338     *
339     * <p>This class has been created long before Java 5 and would
340     * have been a real enum ever since.</p>
341     *
342     * @since 1.1
343     */
344    public static final class UnparseableExtraField implements UnparseableExtraFieldBehavior {
345        /**
346         * Key for "throw an exception" action.
347         */
348        public static final int THROW_KEY = 0;
349        /**
350         * Key for "skip" action.
351         */
352        public static final int SKIP_KEY = 1;
353        /**
354         * Key for "read" action.
355         */
356        public static final int READ_KEY = 2;
357
358        /**
359         * Throw an exception if field cannot be parsed.
360         */
361        public static final UnparseableExtraField THROW
362            = new UnparseableExtraField(THROW_KEY);
363
364        /**
365         * Skip the extra field entirely and don't make its data
366         * available - effectively removing the extra field data.
367         */
368        public static final UnparseableExtraField SKIP
369            = new UnparseableExtraField(SKIP_KEY);
370
371        /**
372         * Read the extra field data into an instance of {@link
373         * UnparseableExtraFieldData UnparseableExtraFieldData}.
374         */
375        public static final UnparseableExtraField READ
376            = new UnparseableExtraField(READ_KEY);
377
378        private final int key;
379
380        private UnparseableExtraField(final int k) {
381            key = k;
382        }
383
384        /**
385         * Key of the action to take.
386         * @return the key
387         */
388        public int getKey() { return key; }
389
390        @Override
391        public ZipExtraField onUnparseableExtraField(byte[] data, int off, int len, boolean local,
392            int claimedLength) throws ZipException {
393            switch(key) {
394            case THROW_KEY:
395                throw new ZipException("Bad extra field starting at "
396                                       + off + ".  Block length of "
397                                       + claimedLength + " bytes exceeds remaining"
398                                       + " data of "
399                                       + (len - WORD)
400                                       + " bytes.");
401            case READ_KEY:
402                final UnparseableExtraFieldData field = new UnparseableExtraFieldData();
403                if (local) {
404                    field.parseFromLocalFileData(data, off, len);
405                } else {
406                    field.parseFromCentralDirectoryData(data, off, len);
407                }
408                return field;
409            case SKIP_KEY:
410                return null;
411            default:
412                throw new ZipException("Unknown UnparseableExtraField key: " + key);
413            }
414        }
415
416    }
417}