1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util.jar;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.access.JavaUtilZipFileAccess;
  30 import sun.security.action.GetPropertyAction;
  31 import sun.security.util.ManifestEntryVerifier;
  32 
  33 import java.io.ByteArrayInputStream;
  34 import java.io.EOFException;
  35 import java.io.File;
  36 import java.io.IOException;
  37 import java.io.InputStream;
  38 import java.lang.ref.SoftReference;
  39 import java.net.URL;
  40 import java.security.CodeSigner;
  41 import java.security.CodeSource;
  42 import java.security.cert.Certificate;
  43 import java.util.ArrayList;
  44 import java.util.Collections;
  45 import java.util.Enumeration;
  46 import java.util.List;
  47 import java.util.Locale;
  48 import java.util.NoSuchElementException;
  49 import java.util.Objects;
  50 import java.util.function.Function;
  51 import java.util.stream.Stream;
  52 import java.util.zip.ZipEntry;
  53 import java.util.zip.ZipException;
  54 import java.util.zip.ZipFile;
  55 
  56 /**
  57  * The {@code JarFile} class is used to read the contents of a jar file
  58  * from any file that can be opened with {@code java.io.RandomAccessFile}.
  59  * It extends the class {@code java.util.zip.ZipFile} with support
  60  * for reading an optional {@code Manifest} entry, and support for
  61  * processing multi-release jar files.  The {@code Manifest} can be used
  62  * to specify meta-information about the jar file and its entries.
  63  *
  64  * <p><a id="multirelease">A multi-release jar file</a> is a jar file that
  65  * contains a manifest with a main attribute named "Multi-Release",
  66  * a set of "base" entries, some of which are public classes with public
  67  * or protected methods that comprise the public interface of the jar file,
  68  * and a set of "versioned" entries contained in subdirectories of the
  69  * "META-INF/versions" directory.  The versioned entries are partitioned by the
  70  * major version of the Java platform.  A versioned entry, with a version
  71  * {@code n}, {@code 8 < n}, in the "META-INF/versions/{n}" directory overrides
  72  * the base entry as well as any entry with a version number {@code i} where
  73  * {@code 8 < i < n}.
  74  *
  75  * <p>By default, a {@code JarFile} for a multi-release jar file is configured
  76  * to process the multi-release jar file as if it were a plain (unversioned) jar
  77  * file, and as such an entry name is associated with at most one base entry.
  78  * The {@code JarFile} may be configured to process a multi-release jar file by
  79  * creating the {@code JarFile} with the
  80  * {@link JarFile#JarFile(File, boolean, int, Runtime.Version)} constructor.  The
  81  * {@code Runtime.Version} object sets a maximum version used when searching for
  82  * versioned entries.  When so configured, an entry name
  83  * can correspond with at most one base entry and zero or more versioned
  84  * entries. A search is required to associate the entry name with the latest
  85  * versioned entry whose version is less than or equal to the maximum version
  86  * (see {@link #getEntry(String)}).
  87  *
  88  * <p>Class loaders that utilize {@code JarFile} to load classes from the
  89  * contents of {@code JarFile} entries should construct the {@code JarFile}
  90  * by invoking the {@link JarFile#JarFile(File, boolean, int, Runtime.Version)}
  91  * constructor with the value {@code Runtime.version()} assigned to the last
  92  * argument.  This assures that classes compatible with the major
  93  * version of the running JVM are loaded from multi-release jar files.
  94  *
  95  * <p> If the {@code verify} flag is on when opening a signed jar file, the content
  96  * of the jar entry is verified against the signature embedded inside the manifest
  97  * that is associated with its {@link JarEntry#getRealName() path name}. For a
  98  * multi-release jar file, the content of a versioned entry is verfieid against
  99  * its own signature and {@link JarEntry#getCodeSigners()} returns its own signers.
 100  *
 101  * Please note that the verification process does not include validating the
 102  * signer's certificate. A caller should inspect the return value of
 103  * {@link JarEntry#getCodeSigners()} to further determine if the signature
 104  * can be trusted.
 105  *
 106  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
 107  * or method in this class will cause a {@link NullPointerException} to be
 108  * thrown.
 109  *
 110  * @implNote
 111  * <div class="block">
 112  * If the API can not be used to configure a {@code JarFile} (e.g. to override
 113  * the configuration of a compiled application or library), two {@code System}
 114  * properties are available.
 115  * <ul>
 116  * <li>
 117  * {@code jdk.util.jar.version} can be assigned a value that is the
 118  * {@code String} representation of a non-negative integer
 119  * {@code <= Runtime.version().feature()}.  The value is used to set the effective
 120  * runtime version to something other than the default value obtained by
 121  * evaluating {@code Runtime.version().feature()}. The effective runtime version
 122  * is the version that the {@link JarFile#JarFile(File, boolean, int, Runtime.Version)}
 123  * constructor uses when the value of the last argument is
 124  * {@code JarFile.runtimeVersion()}.
 125  * </li>
 126  * <li>
 127  * {@code jdk.util.jar.enableMultiRelease} can be assigned one of the three
 128  * {@code String} values <em>true</em>, <em>false</em>, or <em>force</em>.  The
 129  * value <em>true</em>, the default value, enables multi-release jar file
 130  * processing.  The value <em>false</em> disables multi-release jar processing,
 131  * ignoring the "Multi-Release" manifest attribute, and the versioned
 132  * directories in a multi-release jar file if they exist.  Furthermore,
 133  * the method {@link JarFile#isMultiRelease()} returns <em>false</em>. The value
 134  * <em>force</em> causes the {@code JarFile} to be initialized to runtime
 135  * versioning after construction.  It effectively does the same as this code:
 136  * {@code (new JarFile(File, boolean, int, JarFile.runtimeVersion())}.
 137  * </li>
 138  * </ul>
 139  * </div>
 140  *
 141  * @author  David Connelly
 142  * @see     Manifest
 143  * @see     java.util.zip.ZipFile
 144  * @see     java.util.jar.JarEntry
 145  * @since   1.2
 146  */
 147 public class JarFile extends ZipFile {
 148     private static final Runtime.Version BASE_VERSION;
 149     private static final int BASE_VERSION_FEATURE;
 150     private static final Runtime.Version RUNTIME_VERSION;
 151     private static final boolean MULTI_RELEASE_ENABLED;
 152     private static final boolean MULTI_RELEASE_FORCED;
 153     private static final ThreadLocal<Boolean> isInitializing = new ThreadLocal<>();
 154     // The maximum size of array to allocate. Some VMs reserve some header words in an array.
 155     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 156 
 157     private SoftReference<Manifest> manRef;
 158     private JarEntry manEntry;
 159     private JarVerifier jv;
 160     private boolean jvInitialized;
 161     private boolean verify;
 162     private final Runtime.Version version;  // current version
 163     private final int versionFeature;       // version.feature()
 164     private boolean isMultiRelease;         // is jar multi-release?
 165 
 166     // indicates if Class-Path attribute present
 167     private boolean hasClassPathAttribute;
 168     // true if manifest checked for special attributes
 169     private volatile boolean hasCheckedSpecialAttributes;
 170 
 171     private static final JavaUtilZipFileAccess JUZFA;
 172 
 173     static {
 174         // Set up JavaUtilJarAccess in SharedSecrets
 175         SharedSecrets.setJavaUtilJarAccess(new JavaUtilJarAccessImpl());
 176         // Get JavaUtilZipFileAccess from SharedSecrets
 177         JUZFA = SharedSecrets.getJavaUtilZipFileAccess();
 178         // multi-release jar file versions >= 9
 179         BASE_VERSION = Runtime.Version.parse(Integer.toString(8));
 180         BASE_VERSION_FEATURE = BASE_VERSION.feature();
 181         String jarVersion = GetPropertyAction.privilegedGetProperty("jdk.util.jar.version");
 182         int runtimeVersion = Runtime.version().feature();
 183         if (jarVersion != null) {
 184             int jarVer = Integer.parseInt(jarVersion);
 185             runtimeVersion = (jarVer > runtimeVersion)
 186                     ? runtimeVersion
 187                     : Math.max(jarVer, BASE_VERSION_FEATURE);
 188         }
 189         RUNTIME_VERSION = Runtime.Version.parse(Integer.toString(runtimeVersion));
 190         String enableMultiRelease = GetPropertyAction
 191                 .privilegedGetProperty("jdk.util.jar.enableMultiRelease", "true");
 192         switch (enableMultiRelease) {
 193             case "false" -> {
 194                 MULTI_RELEASE_ENABLED = false;
 195                 MULTI_RELEASE_FORCED = false;
 196             }
 197             case "force" -> {
 198                 MULTI_RELEASE_ENABLED = true;
 199                 MULTI_RELEASE_FORCED = true;
 200             }
 201             default -> {
 202                 MULTI_RELEASE_ENABLED = true;
 203                 MULTI_RELEASE_FORCED = false;
 204             }
 205         }
 206     }
 207 
 208     private static final String META_INF = "META-INF/";
 209 
 210     private static final String META_INF_VERSIONS = META_INF + "versions/";
 211 
 212     /**
 213      * The JAR manifest file name.
 214      */
 215     public static final String MANIFEST_NAME = META_INF + "MANIFEST.MF";
 216 
 217     /**
 218      * Returns the version that represents the unversioned configuration of a
 219      * multi-release jar file.
 220      *
 221      * @return the version that represents the unversioned configuration
 222      *
 223      * @since 9
 224      */
 225     public static Runtime.Version baseVersion() {
 226         return BASE_VERSION;
 227     }
 228 
 229     /**
 230      * Returns the version that represents the effective runtime versioned
 231      * configuration of a multi-release jar file.
 232      * <p>
 233      * By default the feature version number of the returned {@code Version} will
 234      * be equal to the feature version number of {@code Runtime.version()}.
 235      * However, if the {@code jdk.util.jar.version} property is set, the
 236      * returned {@code Version} is derived from that property and feature version
 237      * numbers may not be equal.
 238      *
 239      * @return the version that represents the runtime versioned configuration
 240      *
 241      * @since 9
 242      */
 243     public static Runtime.Version runtimeVersion() {
 244         return RUNTIME_VERSION;
 245     }
 246 
 247     /**
 248      * Creates a new {@code JarFile} to read from the specified
 249      * file {@code name}. The {@code JarFile} will be verified if
 250      * it is signed.
 251      * @param name the name of the jar file to be opened for reading
 252      * @throws IOException if an I/O error has occurred
 253      * @throws SecurityException if access to the file is denied
 254      *         by the SecurityManager
 255      */
 256     public JarFile(String name) throws IOException {
 257         this(new File(name), true, ZipFile.OPEN_READ);
 258     }
 259 
 260     /**
 261      * Creates a new {@code JarFile} to read from the specified
 262      * file {@code name}.
 263      * @param name the name of the jar file to be opened for reading
 264      * @param verify whether or not to verify the jar file if
 265      * it is signed.
 266      * @throws IOException if an I/O error has occurred
 267      * @throws SecurityException if access to the file is denied
 268      *         by the SecurityManager
 269      */
 270     public JarFile(String name, boolean verify) throws IOException {
 271         this(new File(name), verify, ZipFile.OPEN_READ);
 272     }
 273 
 274     /**
 275      * Creates a new {@code JarFile} to read from the specified
 276      * {@code File} object. The {@code JarFile} will be verified if
 277      * it is signed.
 278      * @param file the jar file to be opened for reading
 279      * @throws IOException if an I/O error has occurred
 280      * @throws SecurityException if access to the file is denied
 281      *         by the SecurityManager
 282      */
 283     public JarFile(File file) throws IOException {
 284         this(file, true, ZipFile.OPEN_READ);
 285     }
 286 
 287     /**
 288      * Creates a new {@code JarFile} to read from the specified
 289      * {@code File} object.
 290      * @param file the jar file to be opened for reading
 291      * @param verify whether or not to verify the jar file if
 292      * it is signed.
 293      * @throws IOException if an I/O error has occurred
 294      * @throws SecurityException if access to the file is denied
 295      *         by the SecurityManager.
 296      */
 297     public JarFile(File file, boolean verify) throws IOException {
 298         this(file, verify, ZipFile.OPEN_READ);
 299     }
 300 
 301     /**
 302      * Creates a new {@code JarFile} to read from the specified
 303      * {@code File} object in the specified mode.  The mode argument
 304      * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
 305      *
 306      * @param file the jar file to be opened for reading
 307      * @param verify whether or not to verify the jar file if
 308      * it is signed.
 309      * @param mode the mode in which the file is to be opened
 310      * @throws IOException if an I/O error has occurred
 311      * @throws IllegalArgumentException
 312      *         if the {@code mode} argument is invalid
 313      * @throws SecurityException if access to the file is denied
 314      *         by the SecurityManager
 315      * @since 1.3
 316      */
 317     public JarFile(File file, boolean verify, int mode) throws IOException {
 318         this(file, verify, mode, BASE_VERSION);
 319     }
 320 
 321     /**
 322      * Creates a new {@code JarFile} to read from the specified
 323      * {@code File} object in the specified mode.  The mode argument
 324      * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
 325      * The version argument, after being converted to a canonical form, is
 326      * used to configure the {@code JarFile} for processing
 327      * multi-release jar files.
 328      * <p>
 329      * The canonical form derived from the version parameter is
 330      * {@code Runtime.Version.parse(Integer.toString(n))} where {@code n} is
 331      * {@code Math.max(version.feature(), JarFile.baseVersion().feature())}.
 332      *
 333      * @param file the jar file to be opened for reading
 334      * @param verify whether or not to verify the jar file if
 335      * it is signed.
 336      * @param mode the mode in which the file is to be opened
 337      * @param version specifies the release version for a multi-release jar file
 338      * @throws IOException if an I/O error has occurred
 339      * @throws IllegalArgumentException
 340      *         if the {@code mode} argument is invalid
 341      * @throws SecurityException if access to the file is denied
 342      *         by the SecurityManager
 343      * @throws NullPointerException if {@code version} is {@code null}
 344      * @since 9
 345      */
 346     public JarFile(File file, boolean verify, int mode, Runtime.Version version) throws IOException {
 347         super(file, mode);
 348         this.verify = verify;
 349         Objects.requireNonNull(version);
 350         if (MULTI_RELEASE_FORCED || version.feature() == RUNTIME_VERSION.feature()) {
 351             // This deals with the common case where the value from JarFile.runtimeVersion() is passed
 352             this.version = RUNTIME_VERSION;
 353         } else if (version.feature() <= BASE_VERSION_FEATURE) {
 354             // This also deals with the common case where the value from JarFile.baseVersion() is passed
 355             this.version = BASE_VERSION;
 356         } else {
 357             // Canonicalize
 358             this.version = Runtime.Version.parse(Integer.toString(version.feature()));
 359         }
 360         this.versionFeature = this.version.feature();
 361     }
 362 
 363     /**
 364      * Returns the maximum version used when searching for versioned entries.
 365      * <p>
 366      * If this {@code JarFile} is not a multi-release jar file or is not
 367      * configured to be processed as such, then the version returned will be the
 368      * same as that returned from {@link #baseVersion()}.
 369      *
 370      * @return the maximum version
 371      * @since 9
 372      */
 373     public final Runtime.Version getVersion() {
 374         return isMultiRelease() ? this.version : BASE_VERSION;
 375     }
 376 
 377     /**
 378      * Indicates whether or not this jar file is a multi-release jar file.
 379      *
 380      * @return true if this JarFile is a multi-release jar file
 381      * @since 9
 382      */
 383     public final boolean isMultiRelease() {
 384         if (isMultiRelease) {
 385             return true;
 386         }
 387         if (MULTI_RELEASE_ENABLED) {
 388             try {
 389                 checkForSpecialAttributes();
 390             } catch (IOException io) {
 391                 isMultiRelease = false;
 392             }
 393         }
 394         return isMultiRelease;
 395     }
 396 
 397     /**
 398      * Returns the jar file manifest, or {@code null} if none.
 399      *
 400      * @return the jar file manifest, or {@code null} if none
 401      *
 402      * @throws IllegalStateException
 403      *         may be thrown if the jar file has been closed
 404      * @throws IOException  if an I/O error has occurred
 405      */
 406     public Manifest getManifest() throws IOException {
 407         return getManifestFromReference();
 408     }
 409 
 410     private Manifest getManifestFromReference() throws IOException {
 411         Manifest man = manRef != null ? manRef.get() : null;
 412 
 413         if (man == null) {
 414 
 415             JarEntry manEntry = getManEntry();
 416 
 417             // If found then load the manifest
 418             if (manEntry != null) {
 419                 if (verify) {
 420                     byte[] b = getBytes(manEntry);
 421                     if (!jvInitialized) {
 422                         if (JUZFA.getManifestNum(this) == 1) {
 423                             jv = new JarVerifier(manEntry.getName(), b);
 424                         } else {
 425                             if (JarVerifier.debug != null) {
 426                                 JarVerifier.debug.println("Multiple MANIFEST.MF found. Treat JAR file as unsigned");
 427                             }
 428                         }
 429                     }
 430                     man = new Manifest(jv, new ByteArrayInputStream(b), getName());
 431                 } else {
 432                     try (InputStream is = super.getInputStream(manEntry)) {
 433                         man = new Manifest(is, getName());
 434                     }
 435                 }
 436                 manRef = new SoftReference<>(man);
 437             }
 438         }
 439         return man;
 440     }
 441 
 442     /**
 443      * Returns the {@code JarEntry} for the given base entry name or
 444      * {@code null} if not found.
 445      *
 446      * <p>If this {@code JarFile} is a multi-release jar file and is configured
 447      * to be processed as such, then a search is performed to find and return
 448      * a {@code JarEntry} that is the latest versioned entry associated with the
 449      * given entry name.  The returned {@code JarEntry} is the versioned entry
 450      * corresponding to the given base entry name prefixed with the string
 451      * {@code "META-INF/versions/{n}/"}, for the largest value of {@code n} for
 452      * which an entry exists.  If such a versioned entry does not exist, then
 453      * the {@code JarEntry} for the base entry is returned, otherwise
 454      * {@code null} is returned if no entries are found.  The initial value for
 455      * the version {@code n} is the maximum version as returned by the method
 456      * {@link JarFile#getVersion()}.
 457      *
 458      * @param name the jar file entry name
 459      * @return the {@code JarEntry} for the given entry name, or
 460      *         the versioned entry name, or {@code null} if not found
 461      *
 462      * @throws IllegalStateException
 463      *         may be thrown if the jar file has been closed
 464      *
 465      * @see java.util.jar.JarEntry
 466      *
 467      * @implSpec
 468      * <div class="block">
 469      * This implementation invokes {@link JarFile#getEntry(String)}.
 470      * </div>
 471      */
 472     public JarEntry getJarEntry(String name) {
 473         return (JarEntry)getEntry(name);
 474     }
 475 
 476     /**
 477      * Returns the {@code ZipEntry} for the given base entry name or
 478      * {@code null} if not found.
 479      *
 480      * <p>If this {@code JarFile} is a multi-release jar file and is configured
 481      * to be processed as such, then a search is performed to find and return
 482      * a {@code ZipEntry} that is the latest versioned entry associated with the
 483      * given entry name.  The returned {@code ZipEntry} is the versioned entry
 484      * corresponding to the given base entry name prefixed with the string
 485      * {@code "META-INF/versions/{n}/"}, for the largest value of {@code n} for
 486      * which an entry exists.  If such a versioned entry does not exist, then
 487      * the {@code ZipEntry} for the base entry is returned, otherwise
 488      * {@code null} is returned if no entries are found.  The initial value for
 489      * the version {@code n} is the maximum version as returned by the method
 490      * {@link JarFile#getVersion()}.
 491      *
 492      * @param name the jar file entry name
 493      * @return the {@code ZipEntry} for the given entry name or
 494      *         the versioned entry name or {@code null} if not found
 495      *
 496      * @throws IllegalStateException
 497      *         may be thrown if the jar file has been closed
 498      *
 499      * @see java.util.zip.ZipEntry
 500      *
 501      * @implSpec
 502      * <div class="block">
 503      * This implementation may return a versioned entry for the requested name
 504      * even if there is not a corresponding base entry.  This can occur
 505      * if there is a private or package-private versioned entry that matches.
 506      * If a subclass overrides this method, assure that the override method
 507      * invokes {@code super.getEntry(name)} to obtain all versioned entries.
 508      * </div>
 509      */
 510     public ZipEntry getEntry(String name) {
 511         if (isMultiRelease()) {
 512             JarEntry je = getVersionedEntry(name, null);
 513             if (je == null) {
 514                 je = (JarEntry)super.getEntry(name);
 515             }
 516             return je;
 517         } else {
 518             return super.getEntry(name);
 519         }
 520     }
 521 
 522     /**
 523      * Returns an enumeration of the jar file entries.
 524      *
 525      * @return an enumeration of the jar file entries
 526      * @throws IllegalStateException
 527      *         may be thrown if the jar file has been closed
 528      */
 529     public Enumeration<JarEntry> entries() {
 530         return JUZFA.entries(this);
 531     }
 532 
 533     /**
 534      * Returns an ordered {@code Stream} over the jar file entries.
 535      * Entries appear in the {@code Stream} in the order they appear in
 536      * the central directory of the jar file.
 537      *
 538      * @return an ordered {@code Stream} of entries in this jar file
 539      * @throws IllegalStateException if the jar file has been closed
 540      * @since 1.8
 541      */
 542     public Stream<JarEntry> stream() {
 543         return JUZFA.stream(this);
 544     }
 545 
 546     /**
 547      * Returns a {@code Stream} of the versioned jar file entries.
 548      *
 549      * <p>If this {@code JarFile} is a multi-release jar file and is configured to
 550      * be processed as such, then an entry in the stream is the latest versioned entry
 551      * associated with the corresponding base entry name. The maximum version of the
 552      * latest versioned entry is the version returned by {@link #getVersion()}.
 553      * The returned stream may include an entry that only exists as a versioned entry.
 554      *
 555      * If the jar file is not a multi-release jar file or the {@code JarFile} is not
 556      * configured for processing a multi-release jar file, this method returns the
 557      * same stream that {@link #stream()} returns.
 558      *
 559      * @return stream of versioned entries
 560      * @since 10
 561      */
 562     public Stream<JarEntry> versionedStream() {
 563 
 564         if (isMultiRelease()) {
 565             return JUZFA.entryNameStream(this).map(this::getBasename)
 566                                               .filter(Objects::nonNull)
 567                                               .distinct()
 568                                               .map(this::getJarEntry)
 569                                               .filter(Objects::nonNull);
 570         }
 571         return stream();
 572     }
 573 
 574     /**
 575      * Creates a ZipEntry suitable for the given ZipFile.
 576      */
 577     JarEntry entryFor(String name) {
 578         return new JarFileEntry(name);
 579     }
 580 
 581     private String getBasename(String name) {
 582         if (name.startsWith(META_INF_VERSIONS)) {
 583             int off = META_INF_VERSIONS.length();
 584             int index = name.indexOf('/', off);
 585             try {
 586                 // filter out dir META-INF/versions/ and META-INF/versions/*/
 587                 // and any entry with version > 'version'
 588                 if (index == -1 || index == (name.length() - 1) ||
 589                     Integer.parseInt(name, off, index, 10) > versionFeature) {
 590                     return null;
 591                 }
 592             } catch (NumberFormatException x) {
 593                 return null; // remove malformed entries silently
 594             }
 595             // map to its base name
 596             return name.substring(index + 1);
 597         }
 598         return name;
 599     }
 600 
 601     private JarEntry getVersionedEntry(String name, JarEntry defaultEntry) {
 602         if (!name.startsWith(META_INF)) {
 603             int[] versions = JUZFA.getMetaInfVersions(this);
 604             if (BASE_VERSION_FEATURE < versionFeature && versions.length > 0) {
 605                 // search for versioned entry
 606                 for (int i = versions.length - 1; i >= 0; i--) {
 607                     int version = versions[i];
 608                     // skip versions above versionFeature
 609                     if (version > versionFeature) {
 610                         continue;
 611                     }
 612                     // skip versions below base version
 613                     if (version < BASE_VERSION_FEATURE) {
 614                         break;
 615                     }
 616                     JarFileEntry vje = (JarFileEntry)super.getEntry(
 617                             META_INF_VERSIONS + version + "/" + name);
 618                     if (vje != null) {
 619                         return vje.withBasename(name);
 620                     }
 621                 }
 622             }
 623         }
 624         return defaultEntry;
 625     }
 626 
 627     // placeholder for now
 628     String getRealName(JarEntry entry) {
 629         return entry.getRealName();
 630     }
 631 
 632     private class JarFileEntry extends JarEntry {
 633         private String basename;
 634 
 635         JarFileEntry(String name) {
 636             super(name);
 637             this.basename = name;
 638         }
 639 
 640         JarFileEntry(String name, ZipEntry vze) {
 641             super(vze);
 642             this.basename = name;
 643         }
 644 
 645         @Override
 646         public Attributes getAttributes() throws IOException {
 647             Manifest man = JarFile.this.getManifest();
 648             if (man != null) {
 649                 return man.getAttributes(super.getName());
 650             } else {
 651                 return null;
 652             }
 653         }
 654 
 655         @Override
 656         public Certificate[] getCertificates() {
 657             try {
 658                 maybeInstantiateVerifier();
 659             } catch (IOException e) {
 660                 throw new RuntimeException(e);
 661             }
 662             if (certs == null && jv != null) {
 663                 certs = jv.getCerts(JarFile.this, realEntry());
 664             }
 665             return certs == null ? null : certs.clone();
 666         }
 667 
 668         @Override
 669         public CodeSigner[] getCodeSigners() {
 670             try {
 671                 maybeInstantiateVerifier();
 672             } catch (IOException e) {
 673                 throw new RuntimeException(e);
 674             }
 675             if (signers == null && jv != null) {
 676                 signers = jv.getCodeSigners(JarFile.this, realEntry());
 677             }
 678             return signers == null ? null : signers.clone();
 679         }
 680 
 681         @Override
 682         public String getRealName() {
 683             return super.getName();
 684         }
 685 
 686         @Override
 687         public String getName() {
 688             return basename;
 689         }
 690 
 691         JarFileEntry realEntry() {
 692             if (isMultiRelease() && versionFeature != BASE_VERSION_FEATURE) {
 693                 String entryName = super.getName();
 694                 return entryName == basename || entryName.equals(basename) ?
 695                         this : new JarFileEntry(entryName, this);
 696             }
 697             return this;
 698         }
 699 
 700         // changes the basename, returns "this"
 701         JarFileEntry withBasename(String name) {
 702             basename = name;
 703             return this;
 704         }
 705     }
 706 
 707     /*
 708      * Ensures that the JarVerifier has been created if one is
 709      * necessary (i.e., the jar appears to be signed.) This is done as
 710      * a quick check to avoid processing of the manifest for unsigned
 711      * jars.
 712      */
 713     private void maybeInstantiateVerifier() throws IOException {
 714         if (jv != null) {
 715             return;
 716         }
 717 
 718         if (verify) {
 719             // Gets the manifest name, but only if there are
 720             // signature-related files. If so we can assume
 721             // that the jar is signed and that we therefore
 722             // need a JarVerifier and Manifest
 723             String name = JUZFA.getManifestName(this, true);
 724             if (name != null) {
 725                 getManifest();
 726                 return;
 727             }
 728             // No signature-related files; don't instantiate a
 729             // verifier
 730             verify = false;
 731         }
 732     }
 733 
 734     /*
 735      * Initializes the verifier object by reading all the manifest
 736      * entries and passing them to the verifier.
 737      */
 738     private void initializeVerifier() {
 739         ManifestEntryVerifier mev = null;
 740 
 741         // Verify "META-INF/" entries...
 742         try {
 743             List<String> names = JUZFA.getManifestAndSignatureRelatedFiles(this);
 744             for (String name : names) {
 745                 JarEntry e = getJarEntry(name);
 746                 byte[] b;
 747                 if (e == null) {
 748                     throw new JarException("corrupted jar file");
 749                 }
 750                 if (mev == null) {
 751                     mev = new ManifestEntryVerifier
 752                         (getManifestFromReference(), jv.manifestName);
 753                 }
 754                 if (name.equalsIgnoreCase(MANIFEST_NAME)) {
 755                     b = jv.manifestRawBytes;
 756                 } else {
 757                     b = getBytes(e);
 758                 }
 759                 if (b != null && b.length > 0) {
 760                     jv.beginEntry(e, mev);
 761                     jv.update(b.length, b, 0, b.length, mev);
 762                     jv.update(-1, null, 0, 0, mev);
 763                 }
 764             }
 765         } catch (IOException | IllegalArgumentException ex) {
 766             // if we had an error parsing any blocks, just
 767             // treat the jar file as being unsigned
 768             jv = null;
 769             verify = false;
 770             if (JarVerifier.debug != null) {
 771                 JarVerifier.debug.println("jarfile parsing error!");
 772                 ex.printStackTrace();
 773             }
 774         }
 775 
 776         // if after initializing the verifier we have nothing
 777         // signed, we null it out.
 778 
 779         if (jv != null) {
 780 
 781             jv.doneWithMeta();
 782             if (JarVerifier.debug != null) {
 783                 JarVerifier.debug.println("done with meta!");
 784             }
 785 
 786             if (jv.nothingToVerify()) {
 787                 if (JarVerifier.debug != null) {
 788                     JarVerifier.debug.println("nothing to verify!");
 789                 }
 790                 jv = null;
 791                 verify = false;
 792             }
 793         }
 794     }
 795 
 796     /*
 797      * Reads all the bytes for a given entry. Used to process the
 798      * META-INF files.
 799      */
 800     private byte[] getBytes(ZipEntry ze) throws IOException {
 801         try (InputStream is = super.getInputStream(ze)) {
 802             long uncompressedSize = ze.getSize();
 803             if (uncompressedSize > MAX_ARRAY_SIZE) {
 804                 throw new OutOfMemoryError("Required array size too large");
 805             }
 806             int len = (int)uncompressedSize;
 807             int bytesRead;
 808             byte[] b;
 809             // trust specified entry sizes when reasonably small
 810             if (len != -1 && len <= 65535) {
 811                 b = new byte[len];
 812                 bytesRead = is.readNBytes(b, 0, len);
 813             } else {
 814                 b = is.readAllBytes();
 815                 bytesRead = b.length;
 816             }
 817             if (len != -1 && len != bytesRead) {
 818                 throw new EOFException("Expected:" + len + ", read:" + bytesRead);
 819             }
 820             return b;
 821         }
 822     }
 823 
 824     /**
 825      * Returns an input stream for reading the contents of the specified
 826      * zip file entry.
 827      * @param ze the zip file entry
 828      * @return an input stream for reading the contents of the specified
 829      *         zip file entry
 830      * @throws ZipException if a zip file format error has occurred
 831      * @throws IOException if an I/O error has occurred
 832      * @throws SecurityException if any of the jar file entries
 833      *         are incorrectly signed.
 834      * @throws IllegalStateException
 835      *         may be thrown if the jar file has been closed
 836      */
 837     public synchronized InputStream getInputStream(ZipEntry ze)
 838         throws IOException
 839     {
 840         maybeInstantiateVerifier();
 841         if (jv == null) {
 842             return super.getInputStream(ze);
 843         }
 844         if (!jvInitialized) {
 845             initializeVerifier();
 846             jvInitialized = true;
 847             // could be set to null after a call to
 848             // initializeVerifier if we have nothing to
 849             // verify
 850             if (jv == null)
 851                 return super.getInputStream(ze);
 852         }
 853 
 854         // wrap a verifier stream around the real stream
 855         return new JarVerifier.VerifierStream(
 856             getManifestFromReference(),
 857             verifiableEntry(ze),
 858             super.getInputStream(ze),
 859             jv);
 860     }
 861 
 862     private JarEntry verifiableEntry(ZipEntry ze) {
 863         if (ze instanceof JarFileEntry) {
 864             // assure the name and entry match for verification
 865             return ((JarFileEntry)ze).realEntry();
 866         }
 867         ze = getJarEntry(ze.getName());
 868         if (ze instanceof JarFileEntry) {
 869             return ((JarFileEntry)ze).realEntry();
 870         }
 871         return (JarEntry)ze;
 872     }
 873 
 874     // Statics for hand-coded Boyer-Moore search
 875     private static final byte[] CLASSPATH_CHARS =
 876             {'C','L','A','S','S','-','P','A','T','H', ':', ' '};
 877 
 878     // The bad character shift for "class-path: "
 879     private static final byte[] CLASSPATH_LASTOCC;
 880 
 881     // The good suffix shift for "class-path: "
 882     private static final byte[] CLASSPATH_OPTOSFT;
 883 
 884     private static final byte[] MULTIRELEASE_CHARS =
 885             {'M','U','L','T','I','-','R','E','L','E', 'A', 'S', 'E', ':',
 886                     ' ', 'T', 'R', 'U', 'E'};
 887 
 888     // The bad character shift for "multi-release: true"
 889     private static final byte[] MULTIRELEASE_LASTOCC;
 890 
 891     // The good suffix shift for "multi-release: true"
 892     private static final byte[] MULTIRELEASE_OPTOSFT;
 893 
 894     static {
 895         CLASSPATH_LASTOCC = new byte[65];
 896         CLASSPATH_OPTOSFT = new byte[12];
 897         CLASSPATH_LASTOCC[(int)'C' - 32] = 1;
 898         CLASSPATH_LASTOCC[(int)'L' - 32] = 2;
 899         CLASSPATH_LASTOCC[(int)'S' - 32] = 5;
 900         CLASSPATH_LASTOCC[(int)'-' - 32] = 6;
 901         CLASSPATH_LASTOCC[(int)'P' - 32] = 7;
 902         CLASSPATH_LASTOCC[(int)'A' - 32] = 8;
 903         CLASSPATH_LASTOCC[(int)'T' - 32] = 9;
 904         CLASSPATH_LASTOCC[(int)'H' - 32] = 10;
 905         CLASSPATH_LASTOCC[(int)':' - 32] = 11;
 906         CLASSPATH_LASTOCC[(int)' ' - 32] = 12;
 907         for (int i = 0; i < 11; i++) {
 908             CLASSPATH_OPTOSFT[i] = 12;
 909         }
 910         CLASSPATH_OPTOSFT[11] = 1;
 911 
 912         MULTIRELEASE_LASTOCC = new byte[65];
 913         MULTIRELEASE_OPTOSFT = new byte[19];
 914         MULTIRELEASE_LASTOCC[(int)'M' - 32] = 1;
 915         MULTIRELEASE_LASTOCC[(int)'I' - 32] = 5;
 916         MULTIRELEASE_LASTOCC[(int)'-' - 32] = 6;
 917         MULTIRELEASE_LASTOCC[(int)'L' - 32] = 9;
 918         MULTIRELEASE_LASTOCC[(int)'A' - 32] = 11;
 919         MULTIRELEASE_LASTOCC[(int)'S' - 32] = 12;
 920         MULTIRELEASE_LASTOCC[(int)':' - 32] = 14;
 921         MULTIRELEASE_LASTOCC[(int)' ' - 32] = 15;
 922         MULTIRELEASE_LASTOCC[(int)'T' - 32] = 16;
 923         MULTIRELEASE_LASTOCC[(int)'R' - 32] = 17;
 924         MULTIRELEASE_LASTOCC[(int)'U' - 32] = 18;
 925         MULTIRELEASE_LASTOCC[(int)'E' - 32] = 19;
 926         for (int i = 0; i < 17; i++) {
 927             MULTIRELEASE_OPTOSFT[i] = 19;
 928         }
 929         MULTIRELEASE_OPTOSFT[17] = 6;
 930         MULTIRELEASE_OPTOSFT[18] = 1;
 931     }
 932 
 933     private JarEntry getManEntry() {
 934         if (manEntry == null) {
 935             // The manifest entry position is resolved during
 936             // initialization
 937             String name = JUZFA.getManifestName(this, false);
 938             if (name != null) {
 939                 this.manEntry = (JarEntry)super.getEntry(name);
 940             }
 941         }
 942         return manEntry;
 943     }
 944 
 945    /**
 946     * Returns {@code true} iff this JAR file has a manifest with the
 947     * Class-Path attribute
 948     */
 949     boolean hasClassPathAttribute() throws IOException {
 950         checkForSpecialAttributes();
 951         return hasClassPathAttribute;
 952     }
 953 
 954     /**
 955      * Returns true if the pattern {@code src} is found in {@code b}.
 956      * The {@code lastOcc} array is the precomputed bad character shifts.
 957      * Since there are no repeated substring in our search strings,
 958      * the good suffix shifts can be replaced with a comparison.
 959      */
 960     private int match(byte[] src, byte[] b, byte[] lastOcc, byte[] optoSft) {
 961         int len = src.length;
 962         int last = b.length - len;
 963         int i = 0;
 964         next:
 965         while (i <= last) {
 966             for (int j = (len - 1); j >= 0; j--) {
 967                 byte c = b[i + j];
 968                 if (c >= ' ' && c <= 'z') {
 969                     if (c >= 'a') c -= 32; // Canonicalize
 970 
 971                     if (c != src[j]) {
 972                         // no match
 973                         int badShift = lastOcc[c - 32];
 974                         i += Math.max(j + 1 - badShift, optoSft[j]);
 975                         continue next;
 976                     }
 977                 } else {
 978                     // no match, character not valid for name
 979                     i += len;
 980                     continue next;
 981                 }
 982             }
 983             return i;
 984         }
 985         return -1;
 986     }
 987 
 988     /**
 989      * On first invocation, check if the JAR file has the Class-Path
 990      * and the Multi-Release attribute. A no-op on subsequent calls.
 991      */
 992     private void checkForSpecialAttributes() throws IOException {
 993         if (hasCheckedSpecialAttributes) {
 994             return;
 995         }
 996         synchronized (this) {
 997             if (hasCheckedSpecialAttributes) {
 998                 return;
 999             }
1000             JarEntry manEntry = getManEntry();
1001             if (manEntry != null) {
1002                 byte[] b = getBytes(manEntry);
1003                 hasClassPathAttribute = match(CLASSPATH_CHARS, b,
1004                         CLASSPATH_LASTOCC, CLASSPATH_OPTOSFT) != -1;
1005                 // is this a multi-release jar file
1006                 if (MULTI_RELEASE_ENABLED) {
1007                     int i = match(MULTIRELEASE_CHARS, b, MULTIRELEASE_LASTOCC,
1008                             MULTIRELEASE_OPTOSFT);
1009                     if (i != -1) {
1010                         // Read the main attributes of the manifest
1011                         byte[] lbuf = new byte[512];
1012                         Attributes attr = new Attributes();
1013                         attr.read(new Manifest.FastInputStream(
1014                                 new ByteArrayInputStream(b)), lbuf);
1015                         isMultiRelease = Boolean.parseBoolean(
1016                             attr.getValue(Attributes.Name.MULTI_RELEASE));
1017                     }
1018                 }
1019             }
1020             hasCheckedSpecialAttributes = true;
1021         }
1022     }
1023 
1024     synchronized void ensureInitialization() {
1025         try {
1026             maybeInstantiateVerifier();
1027         } catch (IOException e) {
1028             throw new RuntimeException(e);
1029         }
1030         if (jv != null && !jvInitialized) {
1031             isInitializing.set(Boolean.TRUE);
1032             try {
1033                 initializeVerifier();
1034                 jvInitialized = true;
1035             } finally {
1036                 isInitializing.set(Boolean.FALSE);
1037             }
1038         }
1039     }
1040 
1041     static boolean isInitializing() {
1042         Boolean value = isInitializing.get();
1043         return (value == null) ? false : value;
1044     }
1045 
1046     /*
1047      * Returns a versioned {@code JarFileEntry} for the given entry,
1048      * if there is one. Otherwise returns the original entry. This
1049      * is invoked by the {@code entries2} for verifier.
1050      */
1051     JarEntry newEntry(JarEntry je) {
1052         if (isMultiRelease()) {
1053             return getVersionedEntry(je.getName(), je);
1054         }
1055         return je;
1056     }
1057 
1058     /*
1059      * Returns a versioned {@code JarFileEntry} for the given entry
1060      * name, if there is one. Otherwise returns a {@code JarFileEntry}
1061      * with the given name. It is invoked from JarVerifier's entries2
1062      * for {@code singers}.
1063      */
1064     JarEntry newEntry(String name) {
1065         if (isMultiRelease()) {
1066             JarEntry vje = getVersionedEntry(name, null);
1067             if (vje != null) {
1068                 return vje;
1069             }
1070         }
1071         return new JarFileEntry(name);
1072     }
1073 
1074     Enumeration<String> entryNames(CodeSource[] cs) {
1075         ensureInitialization();
1076         if (jv != null) {
1077             return jv.entryNames(this, cs);
1078         }
1079 
1080         /*
1081          * JAR file has no signed content. Is there a non-signing
1082          * code source?
1083          */
1084         boolean includeUnsigned = false;
1085         for (CodeSource c : cs) {
1086             if (c.getCodeSigners() == null) {
1087                 includeUnsigned = true;
1088                 break;
1089             }
1090         }
1091         if (includeUnsigned) {
1092             return unsignedEntryNames();
1093         } else {
1094             return Collections.emptyEnumeration();
1095         }
1096     }
1097 
1098     /**
1099      * Returns an enumeration of the zip file entries
1100      * excluding internal JAR mechanism entries and including
1101      * signed entries missing from the ZIP directory.
1102      */
1103     Enumeration<JarEntry> entries2() {
1104         ensureInitialization();
1105         if (jv != null) {
1106             return jv.entries2(this, JUZFA.entries(JarFile.this));
1107         }
1108 
1109         // screen out entries which are never signed
1110         final var unfilteredEntries = JUZFA.entries(JarFile.this);
1111 
1112         return new Enumeration<>() {
1113 
1114             JarEntry entry;
1115 
1116             public boolean hasMoreElements() {
1117                 if (entry != null) {
1118                     return true;
1119                 }
1120                 while (unfilteredEntries.hasMoreElements()) {
1121                     JarEntry je = unfilteredEntries.nextElement();
1122                     if (JarVerifier.isSigningRelated(je.getName())) {
1123                         continue;
1124                     }
1125                     entry = je;
1126                     return true;
1127                 }
1128                 return false;
1129             }
1130 
1131             public JarEntry nextElement() {
1132                 if (hasMoreElements()) {
1133                     JarEntry je = entry;
1134                     entry = null;
1135                     return newEntry(je);
1136                 }
1137                 throw new NoSuchElementException();
1138             }
1139         };
1140     }
1141 
1142     CodeSource[] getCodeSources(URL url) {
1143         ensureInitialization();
1144         if (jv != null) {
1145             return jv.getCodeSources(this, url);
1146         }
1147 
1148         /*
1149          * JAR file has no signed content. Is there a non-signing
1150          * code source?
1151          */
1152         Enumeration<String> unsigned = unsignedEntryNames();
1153         if (unsigned.hasMoreElements()) {
1154             return new CodeSource[]{JarVerifier.getUnsignedCS(url)};
1155         } else {
1156             return null;
1157         }
1158     }
1159 
1160     private Enumeration<String> unsignedEntryNames() {
1161         final Enumeration<JarEntry> entries = entries();
1162         return new Enumeration<>() {
1163 
1164             String name;
1165 
1166             /*
1167              * Grab entries from ZIP directory but screen out
1168              * metadata.
1169              */
1170             public boolean hasMoreElements() {
1171                 if (name != null) {
1172                     return true;
1173                 }
1174                 while (entries.hasMoreElements()) {
1175                     String value;
1176                     ZipEntry e = entries.nextElement();
1177                     value = e.getName();
1178                     if (e.isDirectory() || JarVerifier.isSigningRelated(value)) {
1179                         continue;
1180                     }
1181                     name = value;
1182                     return true;
1183                 }
1184                 return false;
1185             }
1186 
1187             public String nextElement() {
1188                 if (hasMoreElements()) {
1189                     String value = name;
1190                     name = null;
1191                     return value;
1192                 }
1193                 throw new NoSuchElementException();
1194             }
1195         };
1196     }
1197 
1198     CodeSource getCodeSource(URL url, String name) {
1199         ensureInitialization();
1200         if (jv != null) {
1201             if (jv.eagerValidation) {
1202                 CodeSource cs;
1203                 JarEntry je = getJarEntry(name);
1204                 if (je != null) {
1205                     cs = jv.getCodeSource(url, this, je);
1206                 } else {
1207                     cs = jv.getCodeSource(url, name);
1208                 }
1209                 return cs;
1210             } else {
1211                 return jv.getCodeSource(url, name);
1212             }
1213         }
1214 
1215         return JarVerifier.getUnsignedCS(url);
1216     }
1217 
1218     void setEagerValidation(boolean eager) {
1219         try {
1220             maybeInstantiateVerifier();
1221         } catch (IOException e) {
1222             throw new RuntimeException(e);
1223         }
1224         if (jv != null) {
1225             jv.setEagerValidation(eager);
1226         }
1227     }
1228 
1229     List<Object> getManifestDigests() {
1230         ensureInitialization();
1231         if (jv != null) {
1232             return jv.getManifestDigests();
1233         }
1234         return new ArrayList<>();
1235     }
1236 }