ExtraFieldUtils.java

  1. /*
  2.  *  Licensed to the Apache Software Foundation (ASF) under one or more
  3.  *  contributor license agreements.  See the NOTICE file distributed with
  4.  *  this work for additional information regarding copyright ownership.
  5.  *  The ASF licenses this file to You under the Apache License, Version 2.0
  6.  *  (the "License"); you may not use this file except in compliance with
  7.  *  the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  *  Unless required by applicable law or agreed to in writing, software
  12.  *  distributed under the License is distributed on an "AS IS" BASIS,
  13.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  *  See the License for the specific language governing permissions and
  15.  *  limitations under the License.
  16.  */
  17. package org.apache.commons.compress.archivers.zip;

  18. import java.lang.reflect.Constructor;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.Objects;
  22. import java.util.concurrent.ConcurrentHashMap;
  23. import java.util.concurrent.ConcurrentMap;
  24. import java.util.function.Supplier;
  25. import java.util.zip.ZipException;

  26. /**
  27.  * {@link ZipExtraField} related methods.
  28.  */
  29. // CheckStyle:HideUtilityClassConstructorCheck OFF (bc)
  30. public class ExtraFieldUtils {

  31.     /**
  32.      * "enum" for the possible actions to take if the extra field cannot be parsed.
  33.      * <p>
  34.      * This class has been created long before Java 5 and would have been a real enum ever since.
  35.      * </p>
  36.      *
  37.      * @since 1.1
  38.      */
  39.     public static final class UnparseableExtraField implements UnparseableExtraFieldBehavior {

  40.         /**
  41.          * Key for "throw an exception" action.
  42.          */
  43.         public static final int THROW_KEY = 0;
  44.         /**
  45.          * Key for "skip" action.
  46.          */
  47.         public static final int SKIP_KEY = 1;
  48.         /**
  49.          * Key for "read" action.
  50.          */
  51.         public static final int READ_KEY = 2;

  52.         /**
  53.          * Throw an exception if field cannot be parsed.
  54.          */
  55.         public static final UnparseableExtraField THROW = new UnparseableExtraField(THROW_KEY);

  56.         /**
  57.          * Skip the extra field entirely and don't make its data available - effectively removing the extra field data.
  58.          */
  59.         public static final UnparseableExtraField SKIP = new UnparseableExtraField(SKIP_KEY);

  60.         /**
  61.          * Read the extra field data into an instance of {@link UnparseableExtraFieldData UnparseableExtraFieldData}.
  62.          */
  63.         public static final UnparseableExtraField READ = new UnparseableExtraField(READ_KEY);

  64.         private final int key;

  65.         private UnparseableExtraField(final int k) {
  66.             key = k;
  67.         }

  68.         /**
  69.          * Key of the action to take.
  70.          *
  71.          * @return the key
  72.          */
  73.         public int getKey() {
  74.             return key;
  75.         }

  76.         @Override
  77.         public ZipExtraField onUnparseableExtraField(final byte[] data, final int off, final int len, final boolean local, final int claimedLength)
  78.                 throws ZipException {
  79.             switch (key) {
  80.             case THROW_KEY:
  81.                 throw new ZipException("Bad extra field starting at " + off + ".  Block length of " + claimedLength + " bytes exceeds remaining" + " data of "
  82.                         + (len - WORD) + " bytes.");
  83.             case READ_KEY:
  84.                 final UnparseableExtraFieldData field = new UnparseableExtraFieldData();
  85.                 if (local) {
  86.                     field.parseFromLocalFileData(data, off, len);
  87.                 } else {
  88.                     field.parseFromCentralDirectoryData(data, off, len);
  89.                 }
  90.                 return field;
  91.             case SKIP_KEY:
  92.                 return null;
  93.             default:
  94.                 throw new ZipException("Unknown UnparseableExtraField key: " + key);
  95.             }
  96.         }

  97.     }

  98.     private static final int WORD = 4;

  99.     /**
  100.      * Static registry of known extra fields.
  101.      */
  102.     private static final ConcurrentMap<ZipShort, Supplier<ZipExtraField>> IMPLEMENTATIONS;

  103.     static {
  104.         IMPLEMENTATIONS = new ConcurrentHashMap<>();
  105.         IMPLEMENTATIONS.put(AsiExtraField.HEADER_ID, AsiExtraField::new);
  106.         IMPLEMENTATIONS.put(X5455_ExtendedTimestamp.HEADER_ID, X5455_ExtendedTimestamp::new);
  107.         IMPLEMENTATIONS.put(X7875_NewUnix.HEADER_ID, X7875_NewUnix::new);
  108.         IMPLEMENTATIONS.put(JarMarker.ID, JarMarker::new);
  109.         IMPLEMENTATIONS.put(UnicodePathExtraField.UPATH_ID, UnicodePathExtraField::new);
  110.         IMPLEMENTATIONS.put(UnicodeCommentExtraField.UCOM_ID, UnicodeCommentExtraField::new);
  111.         IMPLEMENTATIONS.put(Zip64ExtendedInformationExtraField.HEADER_ID, Zip64ExtendedInformationExtraField::new);
  112.         IMPLEMENTATIONS.put(X000A_NTFS.HEADER_ID, X000A_NTFS::new);
  113.         IMPLEMENTATIONS.put(X0014_X509Certificates.HEADER_ID, X0014_X509Certificates::new);
  114.         IMPLEMENTATIONS.put(X0015_CertificateIdForFile.HEADER_ID, X0015_CertificateIdForFile::new);
  115.         IMPLEMENTATIONS.put(X0016_CertificateIdForCentralDirectory.HEADER_ID, X0016_CertificateIdForCentralDirectory::new);
  116.         IMPLEMENTATIONS.put(X0017_StrongEncryptionHeader.HEADER_ID, X0017_StrongEncryptionHeader::new);
  117.         IMPLEMENTATIONS.put(X0019_EncryptionRecipientCertificateList.HEADER_ID, X0019_EncryptionRecipientCertificateList::new);
  118.         IMPLEMENTATIONS.put(ResourceAlignmentExtraField.ID, ResourceAlignmentExtraField::new);
  119.     }

  120.     static final ZipExtraField[] EMPTY_ZIP_EXTRA_FIELD_ARRAY = {};

  121.     /**
  122.      * Creates an instance of the appropriate ExtraField, falls back to {@link UnrecognizedExtraField UnrecognizedExtraField}.
  123.      *
  124.      * @param headerId the header identifier
  125.      * @return an instance of the appropriate ExtraField
  126.      */
  127.     public static ZipExtraField createExtraField(final ZipShort headerId) {
  128.         final ZipExtraField field = createExtraFieldNoDefault(headerId);
  129.         if (field != null) {
  130.             return field;
  131.         }
  132.         final UnrecognizedExtraField u = new UnrecognizedExtraField();
  133.         u.setHeaderId(headerId);
  134.         return u;
  135.     }

  136.     /**
  137.      * Creates an instance of the appropriate {@link ZipExtraField}.
  138.      *
  139.      * @param headerId the header identifier
  140.      * @return an instance of the appropriate {@link ZipExtraField} or null if the id is not supported
  141.      * @since 1.19
  142.      */
  143.     public static ZipExtraField createExtraFieldNoDefault(final ZipShort headerId) {
  144.         final Supplier<ZipExtraField> provider = IMPLEMENTATIONS.get(headerId);
  145.         return provider != null ? provider.get() : null;
  146.     }

  147.     /**
  148.      * Fills in the extra field data into the given instance.
  149.      *
  150.      * <p>
  151.      * Calls {@link ZipExtraField#parseFromCentralDirectoryData} or {@link ZipExtraField#parseFromLocalFileData} internally and wraps any
  152.      * {@link ArrayIndexOutOfBoundsException} thrown into a {@link ZipException}.
  153.      * </p>
  154.      *
  155.      * @param ze    the extra field instance to fill
  156.      * @param data  the array of extra field data
  157.      * @param off   offset into data where this field's data starts
  158.      * @param len   the length of this field's data
  159.      * @param local whether the extra field data stems from the local file header. If this is false then the data is part if the central directory header extra
  160.      *              data.
  161.      * @return the filled field, will never be {@code null}
  162.      * @throws ZipException if an error occurs
  163.      *
  164.      * @since 1.19
  165.      */
  166.     public static ZipExtraField fillExtraField(final ZipExtraField ze, final byte[] data, final int off, final int len, final boolean local)
  167.             throws ZipException {
  168.         try {
  169.             if (local) {
  170.                 ze.parseFromLocalFileData(data, off, len);
  171.             } else {
  172.                 ze.parseFromCentralDirectoryData(data, off, len);
  173.             }
  174.             return ze;
  175.         } catch (final ArrayIndexOutOfBoundsException e) {
  176.             throw (ZipException) new ZipException("Failed to parse corrupt ZIP extra field of type " + Integer.toHexString(ze.getHeaderId().getValue()))
  177.                     .initCause(e);
  178.         }
  179.     }

  180.     /**
  181.      * Merges the central directory fields of the given ZipExtraFields.
  182.      *
  183.      * @param data an array of ExtraFields
  184.      * @return an array of bytes
  185.      */
  186.     public static byte[] mergeCentralDirectoryData(final ZipExtraField[] data) {
  187.         final int dataLength = data.length;
  188.         final boolean lastIsUnparseableHolder = dataLength > 0 && data[dataLength - 1] instanceof UnparseableExtraFieldData;
  189.         final int regularExtraFieldCount = lastIsUnparseableHolder ? dataLength - 1 : dataLength;

  190.         int sum = WORD * regularExtraFieldCount;
  191.         for (final ZipExtraField element : data) {
  192.             sum += element.getCentralDirectoryLength().getValue();
  193.         }
  194.         final byte[] result = new byte[sum];
  195.         int start = 0;
  196.         for (int i = 0; i < regularExtraFieldCount; i++) {
  197.             System.arraycopy(data[i].getHeaderId().getBytes(), 0, result, start, 2);
  198.             System.arraycopy(data[i].getCentralDirectoryLength().getBytes(), 0, result, start + 2, 2);
  199.             start += WORD;
  200.             final byte[] central = data[i].getCentralDirectoryData();
  201.             if (central != null) {
  202.                 System.arraycopy(central, 0, result, start, central.length);
  203.                 start += central.length;
  204.             }
  205.         }
  206.         if (lastIsUnparseableHolder) {
  207.             final byte[] central = data[dataLength - 1].getCentralDirectoryData();
  208.             if (central != null) {
  209.                 System.arraycopy(central, 0, result, start, central.length);
  210.             }
  211.         }
  212.         return result;
  213.     }

  214.     /**
  215.      * Merges the local file data fields of the given ZipExtraFields.
  216.      *
  217.      * @param data an array of ExtraFiles
  218.      * @return an array of bytes
  219.      */
  220.     public static byte[] mergeLocalFileDataData(final ZipExtraField[] data) {
  221.         final int dataLength = data.length;
  222.         final boolean lastIsUnparseableHolder = dataLength > 0 && data[dataLength - 1] instanceof UnparseableExtraFieldData;
  223.         final int regularExtraFieldCount = lastIsUnparseableHolder ? dataLength - 1 : dataLength;

  224.         int sum = WORD * regularExtraFieldCount;
  225.         for (final ZipExtraField element : data) {
  226.             sum += element.getLocalFileDataLength().getValue();
  227.         }

  228.         final byte[] result = new byte[sum];
  229.         int start = 0;
  230.         for (int i = 0; i < regularExtraFieldCount; i++) {
  231.             System.arraycopy(data[i].getHeaderId().getBytes(), 0, result, start, 2);
  232.             System.arraycopy(data[i].getLocalFileDataLength().getBytes(), 0, result, start + 2, 2);
  233.             start += WORD;
  234.             final byte[] local = data[i].getLocalFileDataData();
  235.             if (local != null) {
  236.                 System.arraycopy(local, 0, result, start, local.length);
  237.                 start += local.length;
  238.             }
  239.         }
  240.         if (lastIsUnparseableHolder) {
  241.             final byte[] local = data[dataLength - 1].getLocalFileDataData();
  242.             if (local != null) {
  243.                 System.arraycopy(local, 0, result, start, local.length);
  244.             }
  245.         }
  246.         return result;
  247.     }

  248.     /**
  249.      * Parses the array into ExtraFields and populate them with the given data as local file data, throwing an exception if the data cannot be parsed.
  250.      *
  251.      * @param data an array of bytes as it appears in local file data
  252.      * @return an array of ExtraFields
  253.      * @throws ZipException on error
  254.      */
  255.     public static ZipExtraField[] parse(final byte[] data) throws ZipException {
  256.         return parse(data, true, UnparseableExtraField.THROW);
  257.     }

  258.     /**
  259.      * Parses the array into ExtraFields and populate them with the given data, throwing an exception if the data cannot be parsed.
  260.      *
  261.      * @param data  an array of bytes
  262.      * @param local whether data originates from the local file data or the central directory
  263.      * @return an array of ExtraFields
  264.      * @throws ZipException on error
  265.      */
  266.     public static ZipExtraField[] parse(final byte[] data, final boolean local) throws ZipException {
  267.         return parse(data, local, UnparseableExtraField.THROW);
  268.     }

  269.     /**
  270.      * Parses the array into ExtraFields and populate them with the given data.
  271.      *
  272.      * @param data            an array of bytes
  273.      * @param parsingBehavior controls parsing of extra fields.
  274.      * @param local           whether data originates from the local file data or the central directory
  275.      * @return an array of ExtraFields
  276.      * @throws ZipException on error
  277.      *
  278.      * @since 1.19
  279.      */
  280.     public static ZipExtraField[] parse(final byte[] data, final boolean local, final ExtraFieldParsingBehavior parsingBehavior) throws ZipException {
  281.         final List<ZipExtraField> v = new ArrayList<>();
  282.         int start = 0;
  283.         final int dataLength = data.length;
  284.         LOOP: while (start <= dataLength - WORD) {
  285.             final ZipShort headerId = new ZipShort(data, start);
  286.             final int length = new ZipShort(data, start + 2).getValue();
  287.             if (start + WORD + length > dataLength) {
  288.                 final ZipExtraField field = parsingBehavior.onUnparseableExtraField(data, start, dataLength - start, local, length);
  289.                 if (field != null) {
  290.                     v.add(field);
  291.                 }
  292.                 // since we cannot parse the data we must assume
  293.                 // the extra field consumes the whole rest of the
  294.                 // available data
  295.                 break LOOP;
  296.             }
  297.             try {
  298.                 final ZipExtraField ze = Objects.requireNonNull(parsingBehavior.createExtraField(headerId), "createExtraField must not return null");
  299.                 v.add(Objects.requireNonNull(parsingBehavior.fill(ze, data, start + WORD, length, local), "fill must not return null"));
  300.                 start += length + WORD;
  301.             } catch (final InstantiationException | IllegalAccessException e) {
  302.                 throw (ZipException) new ZipException(e.getMessage()).initCause(e);
  303.             }
  304.         }

  305.         return v.toArray(EMPTY_ZIP_EXTRA_FIELD_ARRAY);
  306.     }

  307.     /**
  308.      * Parses the array into ExtraFields and populate them with the given data.
  309.      *
  310.      * @param data              an array of bytes
  311.      * @param local             whether data originates from the local file data or the central directory
  312.      * @param onUnparseableData what to do if the extra field data cannot be parsed.
  313.      * @return an array of ExtraFields
  314.      * @throws ZipException on error
  315.      *
  316.      * @since 1.1
  317.      */
  318.     public static ZipExtraField[] parse(final byte[] data, final boolean local, final UnparseableExtraField onUnparseableData) throws ZipException {
  319.         return parse(data, local, new ExtraFieldParsingBehavior() {

  320.             @Override
  321.             public ZipExtraField createExtraField(final ZipShort headerId) {
  322.                 return ExtraFieldUtils.createExtraField(headerId);
  323.             }

  324.             @Override
  325.             public ZipExtraField fill(final ZipExtraField field, final byte[] data, final int off, final int len, final boolean local) throws ZipException {
  326.                 return fillExtraField(field, data, off, len, local);
  327.             }

  328.             @Override
  329.             public ZipExtraField onUnparseableExtraField(final byte[] data, final int off, final int len, final boolean local, final int claimedLength)
  330.                     throws ZipException {
  331.                 return onUnparseableData.onUnparseableExtraField(data, off, len, local, claimedLength);
  332.             }
  333.         });
  334.     }

  335.     /**
  336.      * Registers a ZipExtraField implementation, overriding a matching existing entry.
  337.      * <p>
  338.      * The given class must have a no-arg constructor and implement the {@link ZipExtraField ZipExtraField interface}.
  339.      * </p>
  340.      *
  341.      * @param clazz the class to register.
  342.      *
  343.      * @deprecated Use {@link ZipArchiveInputStream#setExtraFieldSupport} instead
  344.      *             to not leak instances between archives and applications.
  345.      */
  346.     @Deprecated // note: when dropping update registration to move to a HashMap (static init)
  347.     public static void register(final Class<?> clazz) {
  348.         try {
  349.             final Constructor<? extends ZipExtraField> constructor = clazz.asSubclass(ZipExtraField.class).getConstructor();
  350.             final ZipExtraField zef = clazz.asSubclass(ZipExtraField.class).getConstructor().newInstance();
  351.             IMPLEMENTATIONS.put(zef.getHeaderId(), () -> {
  352.                 try {
  353.                     return constructor.newInstance();
  354.                 } catch (final ReflectiveOperationException e) {
  355.                     throw new IllegalStateException(clazz.toString(), e);
  356.                 }
  357.             });
  358.         } catch (final ReflectiveOperationException e) {
  359.             throw new IllegalArgumentException(clazz.toString(), e);
  360.         }
  361.     }
  362. }