1 /*
   2  * Copyright (c) 1997, 2020, 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 import sun.security.util.SignatureFileVerifier;
  33 
  34 import java.io.ByteArrayInputStream;
  35 import java.io.EOFException;
  36 import java.io.File;
  37 import java.io.IOException;
  38 import java.io.InputStream;
  39 import java.lang.ref.SoftReference;
  40 import java.net.URL;
  41 import java.security.CodeSigner;
  42 import java.security.CodeSource;
  43 import java.security.cert.Certificate;
  44 import java.util.ArrayList;
  45 import java.util.Collections;
  46 import java.util.Enumeration;
  47 import java.util.List;
  48 import java.util.Locale;
  49 import java.util.NoSuchElementException;
  50 import java.util.Objects;
  51 import java.util.function.Function;
  52 import java.util.stream.Stream;
  53 import java.util.zip.ZipEntry;
  54 import java.util.zip.ZipException;
  55 import java.util.zip.ZipFile;
  56 
  57 /**
  58  * The {@code JarFile} class is used to read the contents of a jar file
  59  * from any file that can be opened with {@code java.io.RandomAccessFile}.
  60  * It extends the class {@code java.util.zip.ZipFile} with support
  61  * for reading an optional {@code Manifest} entry, and support for
  62  * processing multi-release jar files.  The {@code Manifest} can be used
  63  * to specify meta-information about the jar file and its entries.
  64  *
  65  * <p><a id="multirelease">A multi-release jar file</a> is a jar file that
  66  * contains a manifest with a main attribute named "Multi-Release",
  67  * a set of "base" entries, some of which are public classes with public
  68  * or protected methods that comprise the public interface of the jar file,
  69  * and a set of "versioned" entries contained in subdirectories of the
  70  * "META-INF/versions" directory.  The versioned entries are partitioned by the
  71  * major version of the Java platform.  A versioned entry, with a version
  72  * {@code n}, {@code 8 < n}, in the "META-INF/versions/{n}" directory overrides
  73  * the base entry as well as any entry with a version number {@code i} where
  74  * {@code 8 < i < n}.
  75  *
  76  * <p>By default, a {@code JarFile} for a multi-release jar file is configured
  77  * to process the multi-release jar file as if it were a plain (unversioned) jar
  78  * file, and as such an entry name is associated with at most one base entry.
  79  * The {@code JarFile} may be configured to process a multi-release jar file by
  80  * creating the {@code JarFile} with the
  81  * {@link JarFile#JarFile(File, boolean, int, Runtime.Version)} constructor.  The
  82  * {@code Runtime.Version} object sets a maximum version used when searching for
  83  * versioned entries.  When so configured, an entry name
  84  * can correspond with at most one base entry and zero or more versioned
  85  * entries. A search is required to associate the entry name with the latest
  86  * versioned entry whose version is less than or equal to the maximum version
  87  * (see {@link #getEntry(String)}).
  88  *
  89  * <p>Class loaders that utilize {@code JarFile} to load classes from the
  90  * contents of {@code JarFile} entries should construct the {@code JarFile}
  91  * by invoking the {@link JarFile#JarFile(File, boolean, int, Runtime.Version)}
  92  * constructor with the value {@code Runtime.version()} assigned to the last
  93  * argument.  This assures that classes compatible with the major
  94  * version of the running JVM are loaded from multi-release jar files.
  95  *
  96  * <p> If the {@code verify} flag is on when opening a signed jar file, the content
  97  * of the jar entry is verified against the signature embedded inside the manifest
  98  * that is associated with its {@link JarEntry#getRealName() path name}. For a
  99  * multi-release jar file, the content of a versioned entry is verfieid against
 100  * its own signature and {@link JarEntry#getCodeSigners()} returns its own signers.
 101  *
 102  * Please note that the verification process does not include validating the
 103  * signer's certificate. A caller should inspect the return value of
 104  * {@link JarEntry#getCodeSigners()} to further determine if the signature
 105  * can be trusted.
 106  *
 107  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
 108  * or method in this class will cause a {@link NullPointerException} to be
 109  * thrown.
 110  *
 111  * @implNote
 112  * <div class="block">
 113  * If the API can not be used to configure a {@code JarFile} (e.g. to override
 114  * the configuration of a compiled application or library), two {@code System}
 115  * properties are available.
 116  * <ul>
 117  * <li>
 118  * {@code jdk.util.jar.version} can be assigned a value that is the
 119  * {@code String} representation of a non-negative integer
 120  * {@code <= Runtime.version().feature()}.  The value is used to set the effective
 121  * runtime version to something other than the default value obtained by
 122  * evaluating {@code Runtime.version().feature()}. The effective runtime version
 123  * is the version that the {@link JarFile#JarFile(File, boolean, int, Runtime.Version)}
 124  * constructor uses when the value of the last argument is
 125  * {@code JarFile.runtimeVersion()}.
 126  * </li>
 127  * <li>
 128  * {@code jdk.util.jar.enableMultiRelease} can be assigned one of the three
 129  * {@code String} values <em>true</em>, <em>false</em>, or <em>force</em>.  The
 130  * value <em>true</em>, the default value, enables multi-release jar file
 131  * processing.  The value <em>false</em> disables multi-release jar processing,
 132  * ignoring the "Multi-Release" manifest attribute, and the versioned
 133  * directories in a multi-release jar file if they exist.  Furthermore,
 134  * the method {@link JarFile#isMultiRelease()} returns <em>false</em>. The value
 135  * <em>force</em> causes the {@code JarFile} to be initialized to runtime
 136  * versioning after construction.  It effectively does the same as this code:
 137  * {@code (new JarFile(File, boolean, int, JarFile.runtimeVersion())}.
 138  * </li>
 139  * </ul>
 140  * </div>
 141  *
 142  * @author  David Connelly
 143  * @see     Manifest
 144  * @see     java.util.zip.ZipFile
 145  * @see     java.util.jar.JarEntry
 146  * @since   1.2
 147  */
 148 public class JarFile extends ZipFile {
 149     private static final Runtime.Version BASE_VERSION;
 150     private static final int BASE_VERSION_FEATURE;
 151     private static final Runtime.Version RUNTIME_VERSION;
 152     private static final boolean MULTI_RELEASE_ENABLED;
 153     private static final boolean MULTI_RELEASE_FORCED;
 154     private static final ThreadLocal<Boolean> isInitializing = new ThreadLocal<>();
 155 
 156     private SoftReference<Manifest> manRef;
 157     private JarEntry manEntry;
 158     private JarVerifier jv;
 159     private boolean jvInitialized;
 160     private boolean verify;
 161     private final Runtime.Version version;  // current version
 162     private final int versionFeature;       // version.feature()
 163     private boolean isMultiRelease;         // is jar multi-release?
 164 
 165     // indicates if Class-Path attribute present
 166     private boolean hasClassPathAttribute;
 167     // true if manifest checked for special attributes
 168     private volatile boolean hasCheckedSpecialAttributes;
 169 
 170     private static final JavaUtilZipFileAccess JUZFA;
 171 
 172     static {
 173         // Set up JavaUtilJarAccess in SharedSecrets
 174         SharedSecrets.setJavaUtilJarAccess(new JavaUtilJarAccessImpl());
 175         // Get JavaUtilZipFileAccess from SharedSecrets
 176         JUZFA = SharedSecrets.getJavaUtilZipFileAccess();
 177         // multi-release jar file versions >= 9
 178         BASE_VERSION = Runtime.Version.parse(Integer.toString(8));
 179         BASE_VERSION_FEATURE = BASE_VERSION.feature();
 180         String jarVersion = GetPropertyAction.privilegedGetProperty("jdk.util.jar.version");
 181         int runtimeVersion = Runtime.version().feature();
 182         if (jarVersion != null) {
 183             int jarVer = Integer.parseInt(jarVersion);
 184             runtimeVersion = (jarVer > runtimeVersion)
 185                     ? runtimeVersion
 186                     : Math.max(jarVer, BASE_VERSION_FEATURE);
 187         }
 188         RUNTIME_VERSION = Runtime.Version.parse(Integer.toString(runtimeVersion));
 189         String enableMultiRelease = GetPropertyAction
 190                 .privilegedGetProperty("jdk.util.jar.enableMultiRelease", "true");
 191         switch (enableMultiRelease) {
 192             case "true":
 193             default:
 194                 MULTI_RELEASE_ENABLED = true;
 195                 MULTI_RELEASE_FORCED = false;
 196                 break;
 197             case "false":
 198                 MULTI_RELEASE_ENABLED = false;
 199                 MULTI_RELEASE_FORCED = false;
 200                 break;
 201             case "force":
 202                 MULTI_RELEASE_ENABLED = true;
 203                 MULTI_RELEASE_FORCED = true;
 204                 break;
 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                         jv = new JarVerifier(b);
 423                     }
 424                     man = new Manifest(jv, new ByteArrayInputStream(b), getName());
 425                 } else {
 426                     man = new Manifest(super.getInputStream(manEntry), getName());
 427                 }
 428                 manRef = new SoftReference<>(man);
 429             }
 430         }
 431         return man;
 432     }
 433 
 434     /**
 435      * Returns the {@code JarEntry} for the given base entry name or
 436      * {@code null} if not found.
 437      *
 438      * <p>If this {@code JarFile} is a multi-release jar file and is configured
 439      * to be processed as such, then a search is performed to find and return
 440      * a {@code JarEntry} that is the latest versioned entry associated with the
 441      * given entry name.  The returned {@code JarEntry} is the versioned entry
 442      * corresponding to the given base entry name prefixed with the string
 443      * {@code "META-INF/versions/{n}/"}, for the largest value of {@code n} for
 444      * which an entry exists.  If such a versioned entry does not exist, then
 445      * the {@code JarEntry} for the base entry is returned, otherwise
 446      * {@code null} is returned if no entries are found.  The initial value for
 447      * the version {@code n} is the maximum version as returned by the method
 448      * {@link JarFile#getVersion()}.
 449      *
 450      * @param name the jar file entry name
 451      * @return the {@code JarEntry} for the given entry name, or
 452      *         the versioned entry name, or {@code null} if not found
 453      *
 454      * @throws IllegalStateException
 455      *         may be thrown if the jar file has been closed
 456      *
 457      * @see java.util.jar.JarEntry
 458      *
 459      * @implSpec
 460      * <div class="block">
 461      * This implementation invokes {@link JarFile#getEntry(String)}.
 462      * </div>
 463      */
 464     public JarEntry getJarEntry(String name) {
 465         return (JarEntry)getEntry(name);
 466     }
 467 
 468     /**
 469      * Returns the {@code ZipEntry} for the given base entry name or
 470      * {@code null} if not found.
 471      *
 472      * <p>If this {@code JarFile} is a multi-release jar file and is configured
 473      * to be processed as such, then a search is performed to find and return
 474      * a {@code ZipEntry} that is the latest versioned entry associated with the
 475      * given entry name.  The returned {@code ZipEntry} is the versioned entry
 476      * corresponding to the given base entry name prefixed with the string
 477      * {@code "META-INF/versions/{n}/"}, for the largest value of {@code n} for
 478      * which an entry exists.  If such a versioned entry does not exist, then
 479      * the {@code ZipEntry} for the base entry is returned, otherwise
 480      * {@code null} is returned if no entries are found.  The initial value for
 481      * the version {@code n} is the maximum version as returned by the method
 482      * {@link JarFile#getVersion()}.
 483      *
 484      * @param name the jar file entry name
 485      * @return the {@code ZipEntry} for the given entry name or
 486      *         the versioned entry name or {@code null} if not found
 487      *
 488      * @throws IllegalStateException
 489      *         may be thrown if the jar file has been closed
 490      *
 491      * @see java.util.zip.ZipEntry
 492      *
 493      * @implSpec
 494      * <div class="block">
 495      * This implementation may return a versioned entry for the requested name
 496      * even if there is not a corresponding base entry.  This can occur
 497      * if there is a private or package-private versioned entry that matches.
 498      * If a subclass overrides this method, assure that the override method
 499      * invokes {@code super.getEntry(name)} to obtain all versioned entries.
 500      * </div>
 501      */
 502     public ZipEntry getEntry(String name) {
 503         if (isMultiRelease()) {
 504             JarEntry je = getVersionedEntry(name, null);
 505             if (je == null) {
 506                 je = getEntry0(name);
 507             }
 508             return je;
 509         } else {
 510             return getEntry0(name);
 511         }
 512     }
 513 
 514     /**
 515      * Returns an enumeration of the jar file entries.
 516      *
 517      * @return an enumeration of the jar file entries
 518      * @throws IllegalStateException
 519      *         may be thrown if the jar file has been closed
 520      */
 521     public Enumeration<JarEntry> entries() {
 522         return JUZFA.entries(this, JarFileEntry::new);
 523     }
 524 
 525     /**
 526      * Returns an ordered {@code Stream} over the jar file entries.
 527      * Entries appear in the {@code Stream} in the order they appear in
 528      * the central directory of the jar file.
 529      *
 530      * @return an ordered {@code Stream} of entries in this jar file
 531      * @throws IllegalStateException if the jar file has been closed
 532      * @since 1.8
 533      */
 534     public Stream<JarEntry> stream() {
 535         return JUZFA.stream(this, JarFileEntry::new);
 536     }
 537 
 538     /**
 539      * Returns a {@code Stream} of the versioned jar file entries.
 540      *
 541      * <p>If this {@code JarFile} is a multi-release jar file and is configured to
 542      * be processed as such, then an entry in the stream is the latest versioned entry
 543      * associated with the corresponding base entry name. The maximum version of the
 544      * latest versioned entry is the version returned by {@link #getVersion()}.
 545      * The returned stream may include an entry that only exists as a versioned entry.
 546      *
 547      * If the jar file is not a multi-release jar file or the {@code JarFile} is not
 548      * configured for processing a multi-release jar file, this method returns the
 549      * same stream that {@link #stream()} returns.
 550      *
 551      * @return stream of versioned entries
 552      * @since 10
 553      */
 554     public Stream<JarEntry> versionedStream() {
 555 
 556         if (isMultiRelease()) {
 557             return JUZFA.entryNameStream(this).map(this::getBasename)
 558                                               .filter(Objects::nonNull)
 559                                               .distinct()
 560                                               .map(this::getJarEntry)
 561                                               .filter(Objects::nonNull);
 562         }
 563         return stream();
 564     }
 565 
 566     /*
 567      * Invokes {@ZipFile}'s getEntry to Return a {@code JarFileEntry} for the
 568      * given entry name or {@code null} if not found.
 569      */
 570     private JarFileEntry getEntry0(String name) {
 571         // Not using a lambda/method reference here to optimize startup time
 572         Function<String, JarEntry> newJarFileEntryFn = new Function<>() {
 573             @Override
 574             public JarEntry apply(String name) {
 575                 return new JarFileEntry(name);
 576             }
 577         };
 578         return (JarFileEntry)JUZFA.getEntry(this, name, newJarFileEntryFn);
 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 = getEntry0(META_INF_VERSIONS + version + "/" + name);
 617                     if (vje != null) {
 618                         return vje.withBasename(name);
 619                     }
 620                 }
 621             }
 622         }
 623         return defaultEntry;
 624     }
 625 
 626     // placeholder for now
 627     String getRealName(JarEntry entry) {
 628         return entry.getRealName();
 629     }
 630 
 631     private class JarFileEntry extends JarEntry {
 632         private String basename;
 633 
 634         JarFileEntry(String name) {
 635             super(name);
 636             this.basename = name;
 637         }
 638 
 639         JarFileEntry(String name, ZipEntry vze) {
 640             super(vze);
 641             this.basename = name;
 642         }
 643 
 644         @Override
 645         public Attributes getAttributes() throws IOException {
 646             Manifest man = JarFile.this.getManifest();
 647             if (man != null) {
 648                 return man.getAttributes(super.getName());
 649             } else {
 650                 return null;
 651             }
 652         }
 653 
 654         @Override
 655         public Certificate[] getCertificates() {
 656             try {
 657                 maybeInstantiateVerifier();
 658             } catch (IOException e) {
 659                 throw new RuntimeException(e);
 660             }
 661             if (certs == null && jv != null) {
 662                 certs = jv.getCerts(JarFile.this, realEntry());
 663             }
 664             return certs == null ? null : certs.clone();
 665         }
 666 
 667         @Override
 668         public CodeSigner[] getCodeSigners() {
 669             try {
 670                 maybeInstantiateVerifier();
 671             } catch (IOException e) {
 672                 throw new RuntimeException(e);
 673             }
 674             if (signers == null && jv != null) {
 675                 signers = jv.getCodeSigners(JarFile.this, realEntry());
 676             }
 677             return signers == null ? null : signers.clone();
 678         }
 679 
 680         @Override
 681         public String getRealName() {
 682             return super.getName();
 683         }
 684 
 685         @Override
 686         public String getName() {
 687             return basename;
 688         }
 689 
 690         JarFileEntry realEntry() {
 691             if (isMultiRelease() && versionFeature != BASE_VERSION_FEATURE) {
 692                 String entryName = super.getName();
 693                 return entryName == basename || entryName.equals(basename) ?
 694                         this : new JarFileEntry(entryName, this);
 695             }
 696             return this;
 697         }
 698 
 699         // changes the basename, returns "this"
 700         JarFileEntry withBasename(String name) {
 701             basename = name;
 702             return this;
 703         }
 704     }
 705 
 706     /*
 707      * Ensures that the JarVerifier has been created if one is
 708      * necessary (i.e., the jar appears to be signed.) This is done as
 709      * a quick check to avoid processing of the manifest for unsigned
 710      * jars.
 711      */
 712     private void maybeInstantiateVerifier() throws IOException {
 713         if (jv != null) {
 714             return;
 715         }
 716 
 717         if (verify) {
 718             // Gets the manifest name, but only if there are
 719             // signature-related files. If so we can assume
 720             // that the jar is signed and that we therefore
 721             // need a JarVerifier and Manifest
 722             String name = JUZFA.getManifestName(this, true);
 723             if (name != null) {
 724                 manEntry = getEntry0(name);
 725                 getManifest();
 726                 return;
 727             }
 728             // No signature-related files; don't instantiate a
 729             // verifier
 730             verify = false;
 731         }
 732     }
 733 
 734 
 735     /*
 736      * Initializes the verifier object by reading all the manifest
 737      * entries and passing them to the verifier.
 738      */
 739     private void initializeVerifier() {
 740         ManifestEntryVerifier mev = null;
 741 
 742         // Verify "META-INF/" entries...
 743         try {
 744             List<String> names = JUZFA.getManifestAndSignatureRelatedFiles(this);
 745             for (String name : names) {
 746                 JarEntry e = getJarEntry(name);
 747                 if (e == null) {
 748                     throw new JarException("corrupted jar file");
 749                 }
 750                 if (mev == null) {
 751                     mev = new ManifestEntryVerifier
 752                         (getManifestFromReference());
 753                 }
 754                 byte[] b = getBytes(e);
 755                 if (b != null && b.length > 0) {
 756                     jv.beginEntry(e, mev);
 757                     jv.update(b.length, b, 0, b.length, mev);
 758                     jv.update(-1, null, 0, 0, mev);
 759                 }
 760             }
 761         } catch (IOException ex) {
 762             // if we had an error parsing any blocks, just
 763             // treat the jar file as being unsigned
 764             jv = null;
 765             verify = false;
 766             if (JarVerifier.debug != null) {
 767                 JarVerifier.debug.println("jarfile parsing error!");
 768                 ex.printStackTrace();
 769             }
 770         }
 771 
 772         // if after initializing the verifier we have nothing
 773         // signed, we null it out.
 774 
 775         if (jv != null) {
 776 
 777             jv.doneWithMeta();
 778             if (JarVerifier.debug != null) {
 779                 JarVerifier.debug.println("done with meta!");
 780             }
 781 
 782             if (jv.nothingToVerify()) {
 783                 if (JarVerifier.debug != null) {
 784                     JarVerifier.debug.println("nothing to verify!");
 785                 }
 786                 jv = null;
 787                 verify = false;
 788             }
 789         }
 790     }
 791 
 792     /*
 793      * Reads all the bytes for a given entry. Used to process the
 794      * META-INF files.
 795      */
 796     private byte[] getBytes(ZipEntry ze) throws IOException {
 797         try (InputStream is = super.getInputStream(ze)) {
 798             int len = (int)ze.getSize();
 799             int bytesRead;
 800             byte[] b;
 801             // trust specified entry sizes when reasonably small
 802             if (len != -1 && len <= 65535) {
 803                 b = new byte[len];
 804                 bytesRead = is.readNBytes(b, 0, len);
 805             } else {
 806                 b = is.readAllBytes();
 807                 bytesRead = b.length;
 808             }
 809             if (len != -1 && len != bytesRead) {
 810                 throw new EOFException("Expected:" + len + ", read:" + bytesRead);
 811             }
 812             return b;
 813         }
 814     }
 815 
 816     /**
 817      * Returns an input stream for reading the contents of the specified
 818      * zip file entry.
 819      * @param ze the zip file entry
 820      * @return an input stream for reading the contents of the specified
 821      *         zip file entry
 822      * @throws ZipException if a zip file format error has occurred
 823      * @throws IOException if an I/O error has occurred
 824      * @throws SecurityException if any of the jar file entries
 825      *         are incorrectly signed.
 826      * @throws IllegalStateException
 827      *         may be thrown if the jar file has been closed
 828      */
 829     public synchronized InputStream getInputStream(ZipEntry ze)
 830         throws IOException
 831     {
 832         maybeInstantiateVerifier();
 833         if (jv == null) {
 834             return super.getInputStream(ze);
 835         }
 836         if (!jvInitialized) {
 837             initializeVerifier();
 838             jvInitialized = true;
 839             // could be set to null after a call to
 840             // initializeVerifier if we have nothing to
 841             // verify
 842             if (jv == null)
 843                 return super.getInputStream(ze);
 844         }
 845 
 846         // wrap a verifier stream around the real stream
 847         return new JarVerifier.VerifierStream(
 848             getManifestFromReference(),
 849             verifiableEntry(ze),
 850             super.getInputStream(ze),
 851             jv);
 852     }
 853 
 854     private JarEntry verifiableEntry(ZipEntry ze) {
 855         if (ze instanceof JarFileEntry) {
 856             // assure the name and entry match for verification
 857             return ((JarFileEntry)ze).realEntry();
 858         }
 859         ze = getJarEntry(ze.getName());
 860         if (ze instanceof JarFileEntry) {
 861             return ((JarFileEntry)ze).realEntry();
 862         }
 863         return (JarEntry)ze;
 864     }
 865 
 866     // Statics for hand-coded Boyer-Moore search
 867     private static final byte[] CLASSPATH_CHARS =
 868             {'C','L','A','S','S','-','P','A','T','H', ':', ' '};
 869 
 870     // The bad character shift for "class-path: "
 871     private static final byte[] CLASSPATH_LASTOCC;
 872 
 873     // The good suffix shift for "class-path: "
 874     private static final byte[] CLASSPATH_OPTOSFT;
 875 
 876     private static final byte[] MULTIRELEASE_CHARS =
 877             {'M','U','L','T','I','-','R','E','L','E', 'A', 'S', 'E', ':',
 878                     ' ', 'T', 'R', 'U', 'E'};
 879 
 880     // The bad character shift for "multi-release: true"
 881     private static final byte[] MULTIRELEASE_LASTOCC;
 882 
 883     // The good suffix shift for "multi-release: true"
 884     private static final byte[] MULTIRELEASE_OPTOSFT;
 885 
 886     static {
 887         CLASSPATH_LASTOCC = new byte[65];
 888         CLASSPATH_OPTOSFT = new byte[12];
 889         CLASSPATH_LASTOCC[(int)'C' - 32] = 1;
 890         CLASSPATH_LASTOCC[(int)'L' - 32] = 2;
 891         CLASSPATH_LASTOCC[(int)'S' - 32] = 5;
 892         CLASSPATH_LASTOCC[(int)'-' - 32] = 6;
 893         CLASSPATH_LASTOCC[(int)'P' - 32] = 7;
 894         CLASSPATH_LASTOCC[(int)'A' - 32] = 8;
 895         CLASSPATH_LASTOCC[(int)'T' - 32] = 9;
 896         CLASSPATH_LASTOCC[(int)'H' - 32] = 10;
 897         CLASSPATH_LASTOCC[(int)':' - 32] = 11;
 898         CLASSPATH_LASTOCC[(int)' ' - 32] = 12;
 899         for (int i = 0; i < 11; i++) {
 900             CLASSPATH_OPTOSFT[i] = 12;
 901         }
 902         CLASSPATH_OPTOSFT[11] = 1;
 903 
 904         MULTIRELEASE_LASTOCC = new byte[65];
 905         MULTIRELEASE_OPTOSFT = new byte[19];
 906         MULTIRELEASE_LASTOCC[(int)'M' - 32] = 1;
 907         MULTIRELEASE_LASTOCC[(int)'I' - 32] = 5;
 908         MULTIRELEASE_LASTOCC[(int)'-' - 32] = 6;
 909         MULTIRELEASE_LASTOCC[(int)'L' - 32] = 9;
 910         MULTIRELEASE_LASTOCC[(int)'A' - 32] = 11;
 911         MULTIRELEASE_LASTOCC[(int)'S' - 32] = 12;
 912         MULTIRELEASE_LASTOCC[(int)':' - 32] = 14;
 913         MULTIRELEASE_LASTOCC[(int)' ' - 32] = 15;
 914         MULTIRELEASE_LASTOCC[(int)'T' - 32] = 16;
 915         MULTIRELEASE_LASTOCC[(int)'R' - 32] = 17;
 916         MULTIRELEASE_LASTOCC[(int)'U' - 32] = 18;
 917         MULTIRELEASE_LASTOCC[(int)'E' - 32] = 19;
 918         for (int i = 0; i < 17; i++) {
 919             MULTIRELEASE_OPTOSFT[i] = 19;
 920         }
 921         MULTIRELEASE_OPTOSFT[17] = 6;
 922         MULTIRELEASE_OPTOSFT[18] = 1;
 923     }
 924 
 925     private JarEntry getManEntry() {
 926         if (manEntry == null) {
 927             // First look up manifest entry using standard name
 928             JarEntry manEntry = getEntry0(MANIFEST_NAME);
 929             if (manEntry == null) {
 930                 // If not found, then iterate through all the "META-INF/"
 931                 // entries to find a match.
 932                 String name = JUZFA.getManifestName(this, false);
 933                 if (name != null) {
 934                     manEntry = getEntry0(name);
 935                 }
 936             }
 937             this.manEntry = manEntry;
 938         }
 939         return manEntry;
 940     }
 941 
 942    /**
 943     * Returns {@code true} iff this JAR file has a manifest with the
 944     * Class-Path attribute
 945     */
 946     boolean hasClassPathAttribute() throws IOException {
 947         checkForSpecialAttributes();
 948         return hasClassPathAttribute;
 949     }
 950 
 951     /**
 952      * Returns true if the pattern {@code src} is found in {@code b}.
 953      * The {@code lastOcc} array is the precomputed bad character shifts.
 954      * Since there are no repeated substring in our search strings,
 955      * the good suffix shifts can be replaced with a comparison.
 956      */
 957     private int match(byte[] src, byte[] b, byte[] lastOcc, byte[] optoSft) {
 958         int len = src.length;
 959         int last = b.length - len;
 960         int i = 0;
 961         next:
 962         while (i <= last) {
 963             for (int j = (len - 1); j >= 0; j--) {
 964                 byte c = b[i + j];
 965                 if (c >= ' ' && c <= 'z') {
 966                     if (c >= 'a') c -= 32; // Canonicalize
 967 
 968                     if (c != src[j]) {
 969                         // no match
 970                         int badShift = lastOcc[c - 32];
 971                         i += Math.max(j + 1 - badShift, optoSft[j]);
 972                         continue next;
 973                     }
 974                 } else {
 975                     // no match, character not valid for name
 976                     i += len;
 977                     continue next;
 978                 }
 979             }
 980             return i;
 981         }
 982         return -1;
 983     }
 984 
 985     /**
 986      * On first invocation, check if the JAR file has the Class-Path
 987      * and the Multi-Release attribute. A no-op on subsequent calls.
 988      */
 989     private void checkForSpecialAttributes() throws IOException {
 990         if (hasCheckedSpecialAttributes) {
 991             return;
 992         }
 993         synchronized (this) {
 994             if (hasCheckedSpecialAttributes) {
 995                 return;
 996             }
 997             JarEntry manEntry = getManEntry();
 998             if (manEntry != null) {
 999                 byte[] b = getBytes(manEntry);
1000                 hasClassPathAttribute = match(CLASSPATH_CHARS, b,
1001                         CLASSPATH_LASTOCC, CLASSPATH_OPTOSFT) != -1;
1002                 // is this a multi-release jar file
1003                 if (MULTI_RELEASE_ENABLED) {
1004                     int i = match(MULTIRELEASE_CHARS, b, MULTIRELEASE_LASTOCC,
1005                             MULTIRELEASE_OPTOSFT);
1006                     if (i != -1) {
1007                         // Read the main attributes of the manifest
1008                         byte[] lbuf = new byte[512];
1009                         Attributes attr = new Attributes();
1010                         attr.read(new Manifest.FastInputStream(
1011                                 new ByteArrayInputStream(b)), lbuf);
1012                         isMultiRelease = Boolean.parseBoolean(
1013                             attr.getValue(Attributes.Name.MULTI_RELEASE));
1014                     }
1015                 }
1016             }
1017             hasCheckedSpecialAttributes = true;
1018         }
1019     }
1020 
1021     synchronized void ensureInitialization() {
1022         try {
1023             maybeInstantiateVerifier();
1024         } catch (IOException e) {
1025             throw new RuntimeException(e);
1026         }
1027         if (jv != null && !jvInitialized) {
1028             isInitializing.set(Boolean.TRUE);
1029             try {
1030                 initializeVerifier();
1031                 jvInitialized = true;
1032             } finally {
1033                 isInitializing.set(Boolean.FALSE);
1034             }
1035         }
1036     }
1037 
1038     static boolean isInitializing() {
1039         Boolean value = isInitializing.get();
1040         return (value == null) ? false : value;
1041     }
1042 
1043     /*
1044      * Returns a versioned {@code JarFileEntry} for the given entry,
1045      * if there is one. Otherwise returns the original entry. This
1046      * is invoked by the {@code entries2} for verifier.
1047      */
1048     JarEntry newEntry(JarEntry je) {
1049         if (isMultiRelease()) {
1050             return getVersionedEntry(je.getName(), je);
1051         }
1052         return je;
1053     }
1054 
1055     /*
1056      * Returns a versioned {@code JarFileEntry} for the given entry
1057      * name, if there is one. Otherwise returns a {@code JarFileEntry}
1058      * with the given name. It is invoked from JarVerifier's entries2
1059      * for {@code singers}.
1060      */
1061     JarEntry newEntry(String name) {
1062         if (isMultiRelease()) {
1063             JarEntry vje = getVersionedEntry(name, null);
1064             if (vje != null) {
1065                 return vje;
1066             }
1067         }
1068         return new JarFileEntry(name);
1069     }
1070 
1071     Enumeration<String> entryNames(CodeSource[] cs) {
1072         ensureInitialization();
1073         if (jv != null) {
1074             return jv.entryNames(this, cs);
1075         }
1076 
1077         /*
1078          * JAR file has no signed content. Is there a non-signing
1079          * code source?
1080          */
1081         boolean includeUnsigned = false;
1082         for (CodeSource c : cs) {
1083             if (c.getCodeSigners() == null) {
1084                 includeUnsigned = true;
1085                 break;
1086             }
1087         }
1088         if (includeUnsigned) {
1089             return unsignedEntryNames();
1090         } else {
1091             return Collections.emptyEnumeration();
1092         }
1093     }
1094 
1095     /**
1096      * Returns an enumeration of the zip file entries
1097      * excluding internal JAR mechanism entries and including
1098      * signed entries missing from the ZIP directory.
1099      */
1100     Enumeration<JarEntry> entries2() {
1101         ensureInitialization();
1102         if (jv != null) {
1103             return jv.entries2(this, JUZFA.entries(JarFile.this,
1104                                                    JarFileEntry::new));
1105         }
1106 
1107         // screen out entries which are never signed
1108         final var unfilteredEntries = JUZFA.entries(JarFile.this, JarFileEntry::new);
1109 
1110         return new Enumeration<>() {
1111 
1112             JarEntry entry;
1113 
1114             public boolean hasMoreElements() {
1115                 if (entry != null) {
1116                     return true;
1117                 }
1118                 while (unfilteredEntries.hasMoreElements()) {
1119                     JarEntry je = unfilteredEntries.nextElement();
1120                     if (JarVerifier.isSigningRelated(je.getName())) {
1121                         continue;
1122                     }
1123                     entry = je;
1124                     return true;
1125                 }
1126                 return false;
1127             }
1128 
1129             public JarEntry nextElement() {
1130                 if (hasMoreElements()) {
1131                     JarEntry je = entry;
1132                     entry = null;
1133                     return newEntry(je);
1134                 }
1135                 throw new NoSuchElementException();
1136             }
1137         };
1138     }
1139 
1140     CodeSource[] getCodeSources(URL url) {
1141         ensureInitialization();
1142         if (jv != null) {
1143             return jv.getCodeSources(this, url);
1144         }
1145 
1146         /*
1147          * JAR file has no signed content. Is there a non-signing
1148          * code source?
1149          */
1150         Enumeration<String> unsigned = unsignedEntryNames();
1151         if (unsigned.hasMoreElements()) {
1152             return new CodeSource[]{JarVerifier.getUnsignedCS(url)};
1153         } else {
1154             return null;
1155         }
1156     }
1157 
1158     private Enumeration<String> unsignedEntryNames() {
1159         final Enumeration<JarEntry> entries = entries();
1160         return new Enumeration<>() {
1161 
1162             String name;
1163 
1164             /*
1165              * Grab entries from ZIP directory but screen out
1166              * metadata.
1167              */
1168             public boolean hasMoreElements() {
1169                 if (name != null) {
1170                     return true;
1171                 }
1172                 while (entries.hasMoreElements()) {
1173                     String value;
1174                     ZipEntry e = entries.nextElement();
1175                     value = e.getName();
1176                     if (e.isDirectory() || JarVerifier.isSigningRelated(value)) {
1177                         continue;
1178                     }
1179                     name = value;
1180                     return true;
1181                 }
1182                 return false;
1183             }
1184 
1185             public String nextElement() {
1186                 if (hasMoreElements()) {
1187                     String value = name;
1188                     name = null;
1189                     return value;
1190                 }
1191                 throw new NoSuchElementException();
1192             }
1193         };
1194     }
1195 
1196     CodeSource getCodeSource(URL url, String name) {
1197         ensureInitialization();
1198         if (jv != null) {
1199             if (jv.eagerValidation) {
1200                 CodeSource cs;
1201                 JarEntry je = getJarEntry(name);
1202                 if (je != null) {
1203                     cs = jv.getCodeSource(url, this, je);
1204                 } else {
1205                     cs = jv.getCodeSource(url, name);
1206                 }
1207                 return cs;
1208             } else {
1209                 return jv.getCodeSource(url, name);
1210             }
1211         }
1212 
1213         return JarVerifier.getUnsignedCS(url);
1214     }
1215 
1216     void setEagerValidation(boolean eager) {
1217         try {
1218             maybeInstantiateVerifier();
1219         } catch (IOException e) {
1220             throw new RuntimeException(e);
1221         }
1222         if (jv != null) {
1223             jv.setEagerValidation(eager);
1224         }
1225     }
1226 
1227     List<Object> getManifestDigests() {
1228         ensureInitialization();
1229         if (jv != null) {
1230             return jv.getManifestDigests();
1231         }
1232         return new ArrayList<>();
1233     }
1234 }