1 /*
   2  * Copyright (c) 1995, 2017, 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.zip;
  27 
  28 import java.io.Closeable;
  29 import java.io.InputStream;
  30 import java.io.IOException;
  31 import java.io.EOFException;
  32 import java.io.File;
  33 import java.io.RandomAccessFile;
  34 import java.io.UncheckedIOException;
  35 import java.lang.ref.Cleaner.Cleanable;
  36 import java.nio.charset.Charset;
  37 import java.nio.charset.StandardCharsets;
  38 import java.nio.file.attribute.BasicFileAttributes;
  39 import java.nio.file.Files;
  40 
  41 import java.util.ArrayDeque;
  42 import java.util.ArrayList;
  43 import java.util.Arrays;
  44 import java.util.Collections;
  45 import java.util.Deque;
  46 import java.util.Enumeration;
  47 import java.util.HashMap;
  48 import java.util.Iterator;
  49 import java.util.Objects;
  50 import java.util.NoSuchElementException;
  51 import java.util.Set;
  52 import java.util.Spliterator;
  53 import java.util.Spliterators;
  54 import java.util.WeakHashMap;
  55 
  56 import java.util.function.Consumer;
  57 import java.util.function.Function;
  58 import java.util.function.IntFunction;
  59 import java.util.jar.JarEntry;
  60 import java.util.stream.Stream;
  61 import java.util.stream.StreamSupport;
  62 import jdk.internal.misc.JavaUtilZipFileAccess;
  63 import jdk.internal.misc.SharedSecrets;
  64 import jdk.internal.misc.VM;
  65 import jdk.internal.perf.PerfCounter;
  66 import jdk.internal.ref.CleanerFactory;
  67 import jdk.internal.vm.annotation.Stable;
  68 
  69 import static java.util.zip.ZipConstants64.*;
  70 import static java.util.zip.ZipUtils.*;
  71 
  72 /**
  73  * This class is used to read entries from a zip file.
  74  *
  75  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
  76  * or method in this class will cause a {@link NullPointerException} to be
  77  * thrown.
  78  *
  79  * @apiNote
  80  * To release resources used by this {@code ZipFile}, the {@link #close()} method
  81  * should be called explicitly or by try-with-resources. Subclasses are responsible
  82  * for the cleanup of resources acquired by the subclass. Subclasses that override
  83  * {@link #finalize()} in order to perform cleanup should be modified to use alternative
  84  * cleanup mechanisms such as {@link java.lang.ref.Cleaner} and remove the overriding
  85  * {@code finalize} method.
  86  *
  87  * @implSpec
  88  * If this {@code ZipFile} has been subclassed and the {@code close} method has
  89  * been overridden, the {@code close} method will be called by the finalization
  90  * when {@code ZipFile} is unreachable. But the subclasses should not depend on
  91  * this specific implementation; the finalization is not reliable and the
  92  * {@code finalize} method is deprecated to be removed.
  93  *
  94  * @author      David Connelly
  95  * @since 1.1
  96  */
  97 public
  98 class ZipFile implements ZipConstants, Closeable {
  99 
 100     private final String name;     // zip file name
 101     private volatile boolean closeRequested;
 102     private final @Stable ZipCoder zc;
 103 
 104     // The "resource" used by this zip file that needs to be
 105     // cleaned after use.
 106     // a) the input streams that need to be closed
 107     // b) the list of cached Inflater objects
 108     // c) the "native" source of this zip file.
 109     private final @Stable CleanableResource res;
 110 
 111     private static final int STORED = ZipEntry.STORED;
 112     private static final int DEFLATED = ZipEntry.DEFLATED;
 113 
 114     /**
 115      * Mode flag to open a zip file for reading.
 116      */
 117     public static final int OPEN_READ = 0x1;
 118 
 119     /**
 120      * Mode flag to open a zip file and mark it for deletion.  The file will be
 121      * deleted some time between the moment that it is opened and the moment
 122      * that it is closed, but its contents will remain accessible via the
 123      * {@code ZipFile} object until either the close method is invoked or the
 124      * virtual machine exits.
 125      */
 126     public static final int OPEN_DELETE = 0x4;
 127 
 128     /**
 129      * Opens a zip file for reading.
 130      *
 131      * <p>First, if there is a security manager, its {@code checkRead}
 132      * method is called with the {@code name} argument as its argument
 133      * to ensure the read is allowed.
 134      *
 135      * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
 136      * decode the entry names and comments.
 137      *
 138      * @param name the name of the zip file
 139      * @throws ZipException if a ZIP format error has occurred
 140      * @throws IOException if an I/O error has occurred
 141      * @throws SecurityException if a security manager exists and its
 142      *         {@code checkRead} method doesn't allow read access to the file.
 143      *
 144      * @see SecurityManager#checkRead(java.lang.String)
 145      */
 146     public ZipFile(String name) throws IOException {
 147         this(new File(name), OPEN_READ);
 148     }
 149 
 150     /**
 151      * Opens a new {@code ZipFile} to read from the specified
 152      * {@code File} object in the specified mode.  The mode argument
 153      * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
 154      *
 155      * <p>First, if there is a security manager, its {@code checkRead}
 156      * method is called with the {@code name} argument as its argument to
 157      * ensure the read is allowed.
 158      *
 159      * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
 160      * decode the entry names and comments
 161      *
 162      * @param file the ZIP file to be opened for reading
 163      * @param mode the mode in which the file is to be opened
 164      * @throws ZipException if a ZIP format error has occurred
 165      * @throws IOException if an I/O error has occurred
 166      * @throws SecurityException if a security manager exists and
 167      *         its {@code checkRead} method
 168      *         doesn't allow read access to the file,
 169      *         or its {@code checkDelete} method doesn't allow deleting
 170      *         the file when the {@code OPEN_DELETE} flag is set.
 171      * @throws IllegalArgumentException if the {@code mode} argument is invalid
 172      * @see SecurityManager#checkRead(java.lang.String)
 173      * @since 1.3
 174      */
 175     public ZipFile(File file, int mode) throws IOException {
 176         this(file, mode, StandardCharsets.UTF_8);
 177     }
 178 
 179     /**
 180      * Opens a ZIP file for reading given the specified File object.
 181      *
 182      * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
 183      * decode the entry names and comments.
 184      *
 185      * @param file the ZIP file to be opened for reading
 186      * @throws ZipException if a ZIP format error has occurred
 187      * @throws IOException if an I/O error has occurred
 188      */
 189     public ZipFile(File file) throws ZipException, IOException {
 190         this(file, OPEN_READ);
 191     }
 192 
 193     /**
 194      * Opens a new {@code ZipFile} to read from the specified
 195      * {@code File} object in the specified mode.  The mode argument
 196      * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
 197      *
 198      * <p>First, if there is a security manager, its {@code checkRead}
 199      * method is called with the {@code name} argument as its argument to
 200      * ensure the read is allowed.
 201      *
 202      * @param file the ZIP file to be opened for reading
 203      * @param mode the mode in which the file is to be opened
 204      * @param charset
 205      *        the {@linkplain java.nio.charset.Charset charset} to
 206      *        be used to decode the ZIP entry name and comment that are not
 207      *        encoded by using UTF-8 encoding (indicated by entry's general
 208      *        purpose flag).
 209      *
 210      * @throws ZipException if a ZIP format error has occurred
 211      * @throws IOException if an I/O error has occurred
 212      *
 213      * @throws SecurityException
 214      *         if a security manager exists and its {@code checkRead}
 215      *         method doesn't allow read access to the file,or its
 216      *         {@code checkDelete} method doesn't allow deleting the
 217      *         file when the {@code OPEN_DELETE} flag is set
 218      *
 219      * @throws IllegalArgumentException if the {@code mode} argument is invalid
 220      *
 221      * @see SecurityManager#checkRead(java.lang.String)
 222      *
 223      * @since 1.7
 224      */
 225     public ZipFile(File file, int mode, Charset charset) throws IOException
 226     {
 227         if (((mode & OPEN_READ) == 0) ||
 228             ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
 229             throw new IllegalArgumentException("Illegal mode: 0x"+
 230                                                Integer.toHexString(mode));
 231         }
 232         String name = file.getPath();
 233         SecurityManager sm = System.getSecurityManager();
 234         if (sm != null) {
 235             sm.checkRead(name);
 236             if ((mode & OPEN_DELETE) != 0) {
 237                 sm.checkDelete(name);
 238             }
 239         }
 240         Objects.requireNonNull(charset, "charset");
 241 
 242         this.zc = ZipCoder.get(charset);
 243         this.name = name;
 244         long t0 = System.nanoTime();
 245 
 246         this.res = CleanableResource.get(this, file, mode);
 247 
 248         PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
 249         PerfCounter.getZipFileCount().increment();
 250     }
 251 
 252     /**
 253      * Opens a zip file for reading.
 254      *
 255      * <p>First, if there is a security manager, its {@code checkRead}
 256      * method is called with the {@code name} argument as its argument
 257      * to ensure the read is allowed.
 258      *
 259      * @param name the name of the zip file
 260      * @param charset
 261      *        the {@linkplain java.nio.charset.Charset charset} to
 262      *        be used to decode the ZIP entry name and comment that are not
 263      *        encoded by using UTF-8 encoding (indicated by entry's general
 264      *        purpose flag).
 265      *
 266      * @throws ZipException if a ZIP format error has occurred
 267      * @throws IOException if an I/O error has occurred
 268      * @throws SecurityException
 269      *         if a security manager exists and its {@code checkRead}
 270      *         method doesn't allow read access to the file
 271      *
 272      * @see SecurityManager#checkRead(java.lang.String)
 273      *
 274      * @since 1.7
 275      */
 276     public ZipFile(String name, Charset charset) throws IOException
 277     {
 278         this(new File(name), OPEN_READ, charset);
 279     }
 280 
 281     /**
 282      * Opens a ZIP file for reading given the specified File object.
 283      *
 284      * @param file the ZIP file to be opened for reading
 285      * @param charset
 286      *        The {@linkplain java.nio.charset.Charset charset} to be
 287      *        used to decode the ZIP entry name and comment (ignored if
 288      *        the <a href="package-summary.html#lang_encoding"> language
 289      *        encoding bit</a> of the ZIP entry's general purpose bit
 290      *        flag is set).
 291      *
 292      * @throws ZipException if a ZIP format error has occurred
 293      * @throws IOException if an I/O error has occurred
 294      *
 295      * @since 1.7
 296      */
 297     public ZipFile(File file, Charset charset) throws IOException
 298     {
 299         this(file, OPEN_READ, charset);
 300     }
 301 
 302     /**
 303      * Returns the zip file comment, or null if none.
 304      *
 305      * @return the comment string for the zip file, or null if none
 306      *
 307      * @throws IllegalStateException if the zip file has been closed
 308      *
 309      * @since 1.7
 310      */
 311     public String getComment() {
 312         synchronized (this) {
 313             ensureOpen();
 314             if (res.zsrc.comment == null) {
 315                 return null;
 316             }
 317             return zc.toString(res.zsrc.comment);
 318         }
 319     }
 320 
 321     /**
 322      * Returns the zip file entry for the specified name, or null
 323      * if not found.
 324      *
 325      * @param name the name of the entry
 326      * @return the zip file entry, or null if not found
 327      * @throws IllegalStateException if the zip file has been closed
 328      */
 329     public ZipEntry getEntry(String name) {
 330         return getEntry(name, ZipEntry::new);
 331     }
 332 
 333     /*
 334      * Returns the zip file entry for the specified name, or null
 335      * if not found.
 336      *
 337      * @param name the name of the entry
 338      * @param func the function that creates the returned entry
 339      *
 340      * @return the zip file entry, or null if not found
 341      * @throws IllegalStateException if the zip file has been closed
 342      */
 343     private ZipEntry getEntry(String name, Function<String, ? extends ZipEntry> func) {
 344         Objects.requireNonNull(name, "name");
 345         synchronized (this) {
 346             ensureOpen();
 347             byte[] bname = zc.getBytes(name);
 348             int pos = res.zsrc.getEntryPos(bname, true);
 349             if (pos != -1) {
 350                 return getZipEntry(name, bname, pos, func);
 351             }
 352         }
 353         return null;
 354     }
 355 
 356     /**
 357      * Returns an input stream for reading the contents of the specified
 358      * zip file entry.
 359      * <p>
 360      * Closing this ZIP file will, in turn, close all input streams that
 361      * have been returned by invocations of this method.
 362      *
 363      * @param entry the zip file entry
 364      * @return the input stream for reading the contents of the specified
 365      * zip file entry.
 366      * @throws ZipException if a ZIP format error has occurred
 367      * @throws IOException if an I/O error has occurred
 368      * @throws IllegalStateException if the zip file has been closed
 369      */
 370     public InputStream getInputStream(ZipEntry entry) throws IOException {
 371         Objects.requireNonNull(entry, "entry");
 372         int pos = -1;
 373         ZipFileInputStream in;
 374         Source zsrc = res.zsrc;
 375         Set<InputStream> istreams = res.istreams;
 376         synchronized (this) {
 377             ensureOpen();
 378             if (Objects.equals(lastEntryName, entry.name)) {
 379                 pos = lastEntryPos;
 380             } else if (!zc.isUTF8() && (entry.flag & EFS) != 0) {
 381                 pos = zsrc.getEntryPos(zc.getBytesUTF8(entry.name), false);
 382             } else {
 383                 pos = zsrc.getEntryPos(zc.getBytes(entry.name), false);
 384             }
 385             if (pos == -1) {
 386                 return null;
 387             }
 388             in = new ZipFileInputStream(zsrc.cen, pos);
 389             switch (CENHOW(zsrc.cen, pos)) {
 390             case STORED:
 391                 synchronized (istreams) {
 392                     istreams.add(in);
 393                 }
 394                 return in;
 395             case DEFLATED:
 396                 // Inflater likes a bit of slack
 397                 // MORE: Compute good size for inflater stream:
 398                 long size = CENLEN(zsrc.cen, pos) + 2;
 399                 if (size > 65536) {
 400                     size = 8192;
 401                 }
 402                 if (size <= 0) {
 403                     size = 4096;
 404                 }
 405                 InputStream is = new ZipFileInflaterInputStream(in, res, (int)size);
 406                 synchronized (istreams) {
 407                     istreams.add(is);
 408                 }
 409                 return is;
 410             default:
 411                 throw new ZipException("invalid compression method");
 412             }
 413         }
 414     }
 415 
 416     private static class InflaterCleanupAction implements Runnable {
 417         private final Inflater inf;
 418         private final CleanableResource res;
 419 
 420         InflaterCleanupAction(Inflater inf, CleanableResource res) {
 421             this.inf = inf;
 422             this.res = res;
 423         }
 424 
 425         @Override
 426         public void run() {
 427             res.releaseInflater(inf);
 428         }
 429     }
 430 
 431     private class ZipFileInflaterInputStream extends InflaterInputStream {
 432         private volatile boolean closeRequested;
 433         private boolean eof = false;
 434         private final Cleanable cleanable;
 435 
 436         ZipFileInflaterInputStream(ZipFileInputStream zfin,
 437                                    CleanableResource res, int size) {
 438             this(zfin, res, res.getInflater(), size);
 439         }
 440 
 441         private ZipFileInflaterInputStream(ZipFileInputStream zfin,
 442                                            CleanableResource res,
 443                                            Inflater inf, int size) {
 444             super(zfin, inf, size);
 445             this.cleanable = CleanerFactory.cleaner().register(this,
 446                     new InflaterCleanupAction(inf, res));
 447         }
 448 
 449         public void close() throws IOException {
 450             if (closeRequested)
 451                 return;
 452             closeRequested = true;
 453             super.close();
 454             synchronized (res.istreams) {
 455                 res.istreams.remove(this);
 456             }
 457             cleanable.clean();
 458         }
 459 
 460         // Override fill() method to provide an extra "dummy" byte
 461         // at the end of the input stream. This is required when
 462         // using the "nowrap" Inflater option.
 463         protected void fill() throws IOException {
 464             if (eof) {
 465                 throw new EOFException("Unexpected end of ZLIB input stream");
 466             }
 467             len = in.read(buf, 0, buf.length);
 468             if (len == -1) {
 469                 buf[0] = 0;
 470                 len = 1;
 471                 eof = true;
 472             }
 473             inf.setInput(buf, 0, len);
 474         }
 475 
 476         public int available() throws IOException {
 477             if (closeRequested)
 478                 return 0;
 479             long avail = ((ZipFileInputStream)in).size() - inf.getBytesWritten();
 480             return (avail > (long) Integer.MAX_VALUE ?
 481                     Integer.MAX_VALUE : (int) avail);
 482         }
 483     }
 484 
 485     /**
 486      * Returns the path name of the ZIP file.
 487      * @return the path name of the ZIP file
 488      */
 489     public String getName() {
 490         return name;
 491     }
 492 
 493     private class ZipEntryIterator<T extends ZipEntry>
 494             implements Enumeration<T>, Iterator<T> {
 495 
 496         private int i = 0;
 497         private final int entryCount;
 498         private final Function<String, T> gen;
 499 
 500         public ZipEntryIterator(int entryCount, Function<String, T> gen) {
 501             this.entryCount = entryCount;
 502             this.gen = gen;
 503         }
 504 
 505         @Override
 506         public boolean hasMoreElements() {
 507             return hasNext();
 508         }
 509 
 510         @Override
 511         public boolean hasNext() {
 512             return i < entryCount;
 513         }
 514 
 515         @Override
 516         public T nextElement() {
 517             return next();
 518         }
 519 
 520         @Override
 521         @SuppressWarnings("unchecked")
 522         public T  next() {
 523             synchronized (ZipFile.this) {
 524                 ensureOpen();
 525                 if (!hasNext()) {
 526                     throw new NoSuchElementException();
 527                 }
 528                 // each "entry" has 3 ints in table entries
 529                 return (T)getZipEntry(null, null, res.zsrc.getEntryPos(i++ * 3), gen);
 530             }
 531         }
 532 
 533         @Override
 534         public Iterator<T> asIterator() {
 535             return this;
 536         }
 537     }
 538 
 539     /**
 540      * Returns an enumeration of the ZIP file entries.
 541      * @return an enumeration of the ZIP file entries
 542      * @throws IllegalStateException if the zip file has been closed
 543      */
 544     public Enumeration<? extends ZipEntry> entries() {
 545         synchronized (this) {
 546             ensureOpen();
 547             return new ZipEntryIterator<ZipEntry>(res.zsrc.total, ZipEntry::new);
 548         }
 549     }
 550 
 551     private Enumeration<JarEntry> entries(Function<String, JarEntry> func) {
 552         synchronized (this) {
 553             ensureOpen();
 554             return new ZipEntryIterator<JarEntry>(res.zsrc.total, func);
 555         }
 556     }
 557 
 558     private class EntrySpliterator<T> extends Spliterators.AbstractSpliterator<T> {
 559         private int index;
 560         private final int fence;
 561         private final IntFunction<T> gen;
 562 
 563         EntrySpliterator(int index, int fence, IntFunction<T> gen) {
 564             super((long)fence,
 565                   Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE |
 566                   Spliterator.NONNULL);
 567             this.index = index;
 568             this.fence = fence;
 569             this.gen = gen;
 570         }
 571 
 572         @Override
 573         public boolean tryAdvance(Consumer<? super T> action) {
 574             if (action == null)
 575                 throw new NullPointerException();
 576             if (index >= 0 && index < fence) {
 577                 synchronized (ZipFile.this) {
 578                     ensureOpen();
 579                     action.accept(gen.apply(res.zsrc.getEntryPos(index++ * 3)));
 580                 }
 581                 return true;
 582             }
 583             return false;
 584         }
 585     }
 586 
 587     /**
 588      * Returns an ordered {@code Stream} over the ZIP file entries.
 589      *
 590      * Entries appear in the {@code Stream} in the order they appear in
 591      * the central directory of the ZIP file.
 592      *
 593      * @return an ordered {@code Stream} of entries in this ZIP file
 594      * @throws IllegalStateException if the zip file has been closed
 595      * @since 1.8
 596      */
 597     public Stream<? extends ZipEntry> stream() {
 598         synchronized (this) {
 599             ensureOpen();
 600             return StreamSupport.stream(new EntrySpliterator<>(0, res.zsrc.total,
 601                 pos -> getZipEntry(null, null, pos, ZipEntry::new)), false);
 602        }
 603     }
 604 
 605     private String getEntryName(int pos) {
 606         byte[] cen = res.zsrc.cen;
 607         int nlen = CENNAM(cen, pos);
 608         if (!zc.isUTF8() && (CENFLG(cen, pos) & EFS) != 0) {
 609             return zc.toStringUTF8(cen, pos + CENHDR, nlen);
 610         } else {
 611             return zc.toString(cen, pos + CENHDR, nlen);
 612         }
 613     }
 614 
 615     /*
 616      * Returns an ordered {@code Stream} over the zip file entry names.
 617      *
 618      * Entry names appear in the {@code Stream} in the order they appear in
 619      * the central directory of the ZIP file.
 620      *
 621      * @return an ordered {@code Stream} of entry names in this zip file
 622      * @throws IllegalStateException if the zip file has been closed
 623      * @since 10
 624      */
 625     private Stream<String> entryNameStream() {
 626         synchronized (this) {
 627             ensureOpen();
 628             return StreamSupport.stream(
 629                 new EntrySpliterator<>(0, res.zsrc.total, this::getEntryName), false);
 630         }
 631     }
 632 
 633     /*
 634      * Returns an ordered {@code Stream} over the zip file entries.
 635      *
 636      * Entries appear in the {@code Stream} in the order they appear in
 637      * the central directory of the jar file.
 638      *
 639      * @param func the function that creates the returned entry
 640      * @return an ordered {@code Stream} of entries in this zip file
 641      * @throws IllegalStateException if the zip file has been closed
 642      * @since 10
 643      */
 644     private Stream<JarEntry> stream(Function<String, JarEntry> func) {
 645         synchronized (this) {
 646             ensureOpen();
 647             return StreamSupport.stream(new EntrySpliterator<>(0, res.zsrc.total,
 648                 pos -> (JarEntry)getZipEntry(null, null, pos, func)), false);
 649         }
 650     }
 651 
 652     private String lastEntryName;
 653     private int lastEntryPos;
 654 
 655     /* Checks ensureOpen() before invoke this method */
 656     private ZipEntry getZipEntry(String name, byte[] bname, int pos,
 657                                  Function<String, ? extends ZipEntry> func) {
 658         byte[] cen = res.zsrc.cen;
 659         int nlen = CENNAM(cen, pos);
 660         int elen = CENEXT(cen, pos);
 661         int clen = CENCOM(cen, pos);
 662         int flag = CENFLG(cen, pos);
 663         if (name == null || bname.length != nlen) {
 664             // to use the entry name stored in cen, if the passed in name is
 665             // (1) null, invoked from iterator, or
 666             // (2) not equal to the name stored, a slash is appended during
 667             // getEntryPos() search.
 668             if (!zc.isUTF8() && (flag & EFS) != 0) {
 669                 name = zc.toStringUTF8(cen, pos + CENHDR, nlen);
 670             } else {
 671                 name = zc.toString(cen, pos + CENHDR, nlen);
 672             }
 673         }
 674         ZipEntry e = func.apply(name);    //ZipEntry e = new ZipEntry(name);
 675         e.flag = flag;
 676         e.xdostime = CENTIM(cen, pos);
 677         e.crc = CENCRC(cen, pos);
 678         e.size = CENLEN(cen, pos);
 679         e.csize = CENSIZ(cen, pos);
 680         e.method = CENHOW(cen, pos);
 681         if (elen != 0) {
 682             int start = pos + CENHDR + nlen;
 683             e.setExtra0(Arrays.copyOfRange(cen, start, start + elen), true);
 684         }
 685         if (clen != 0) {
 686             int start = pos + CENHDR + nlen + elen;
 687             if (!zc.isUTF8() && (flag & EFS) != 0) {
 688                 e.comment = zc.toStringUTF8(cen, start, clen);
 689             } else {
 690                 e.comment = zc.toString(cen, start, clen);
 691             }
 692         }
 693         lastEntryName = e.name;
 694         lastEntryPos = pos;
 695         return e;
 696     }
 697 
 698     /**
 699      * Returns the number of entries in the ZIP file.
 700      *
 701      * @return the number of entries in the ZIP file
 702      * @throws IllegalStateException if the zip file has been closed
 703      */
 704     public int size() {
 705         synchronized (this) {
 706             ensureOpen();
 707             return res.zsrc.total;
 708         }
 709     }
 710 
 711     private static class CleanableResource implements Runnable {
 712         // The outstanding inputstreams that need to be closed
 713         final Set<InputStream> istreams;
 714 
 715         // List of cached Inflater objects for decompression
 716         Deque<Inflater> inflaterCache;
 717 
 718         final Cleanable cleanable;
 719 
 720         Source zsrc;
 721 
 722         CleanableResource(ZipFile zf, File file, int mode) throws IOException {
 723             this.cleanable = CleanerFactory.cleaner().register(zf, this);
 724             this.istreams = Collections.newSetFromMap(new WeakHashMap<>());
 725             this.inflaterCache = new ArrayDeque<>();
 726             this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0);
 727         }
 728 
 729         void clean() {
 730             cleanable.clean();
 731         }
 732 
 733         /*
 734          * Gets an inflater from the list of available inflaters or allocates
 735          * a new one.
 736          */
 737         Inflater getInflater() {
 738             Inflater inf;
 739             synchronized (inflaterCache) {
 740                 if ((inf = inflaterCache.poll()) != null) {
 741                     return inf;
 742                 }
 743             }
 744             return new Inflater(true);
 745         }
 746 
 747         /*
 748          * Releases the specified inflater to the list of available inflaters.
 749          */
 750         void releaseInflater(Inflater inf) {
 751             Deque<Inflater> inflaters = this.inflaterCache;
 752             if (inflaters != null) {
 753                 synchronized (inflaters) {
 754                     // double checked!
 755                     if (inflaters == this.inflaterCache) {
 756                         inf.reset();
 757                         inflaters.add(inf);
 758                         return;
 759                     }
 760                 }
 761             }
 762             // inflaters cache already closed - just end it.
 763             inf.end();
 764         }
 765 
 766         public void run() {
 767             IOException ioe = null;
 768 
 769             // Release cached inflaters and close the cache first
 770             Deque<Inflater> inflaters = this.inflaterCache;
 771             if (inflaters != null) {
 772                 synchronized (inflaters) {
 773                     // no need to double-check as only one thread gets a
 774                     // chance to execute run() (Cleaner guarantee)...
 775                     Inflater inf;
 776                     while ((inf = inflaters.poll()) != null) {
 777                         inf.end();
 778                     }
 779                     // close inflaters cache
 780                     this.inflaterCache = null;
 781                 }
 782             }
 783 
 784             // Close streams, release their inflaters
 785             if (istreams != null) {
 786                 synchronized (istreams) {
 787                     if (!istreams.isEmpty()) {
 788                         InputStream[] copy = istreams.toArray(new InputStream[0]);
 789                         istreams.clear();
 790                         for (InputStream is : copy) {
 791                             try {
 792                                 is.close();
 793                             }  catch (IOException e) {
 794                                 if (ioe == null) ioe = e;
 795                                 else ioe.addSuppressed(e);
 796                             }
 797                         }
 798                     }
 799                 }
 800             }
 801 
 802             // Release zip src
 803             if (zsrc != null) {
 804                 synchronized (zsrc) {
 805                     try {
 806                         Source.release(zsrc);
 807                         zsrc = null;
 808                      }  catch (IOException e) {
 809                          if (ioe == null) ioe = e;
 810                          else ioe.addSuppressed(e);
 811                     }
 812                 }
 813             }
 814             if (ioe != null) {
 815                 throw new UncheckedIOException(ioe);
 816             }
 817         }
 818 
 819         CleanableResource(File file, int mode)
 820             throws IOException {
 821             this.cleanable = null;
 822             this.istreams = Collections.newSetFromMap(new WeakHashMap<>());
 823             this.inflaterCache = new ArrayDeque<>();
 824             this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0);
 825         }
 826 
 827         /*
 828          * If {@code ZipFile} has been subclassed and the {@code close} method is
 829          * overridden, uses the {@code finalizer} mechanism for resource cleanup.
 830          * So {@code close} method can be called when the the {@code ZipFile} is
 831          * unreachable. This mechanism will be removed when {@code finalize} method
 832          * is removed from {@code ZipFile}.
 833          */
 834         static CleanableResource get(ZipFile zf, File file, int mode)
 835             throws IOException {
 836             Class<?> clz = zf.getClass();
 837             while (clz != ZipFile.class) {
 838                 try {
 839                     clz.getDeclaredMethod("close");
 840                     return new FinalizableResource(zf, file, mode);
 841                 } catch (NoSuchMethodException nsme) {}
 842                 clz = clz.getSuperclass();
 843             }
 844             return new CleanableResource(zf, file, mode);
 845         }
 846 
 847         static class FinalizableResource extends CleanableResource {
 848             ZipFile zf;
 849             FinalizableResource(ZipFile zf, File file, int mode)
 850                 throws IOException {
 851                 super(file, mode);
 852                 this.zf = zf;
 853             }
 854 
 855             @Override
 856             void clean() {
 857                 run();
 858             }
 859 
 860             @Override
 861             @SuppressWarnings("deprecation")
 862             protected void finalize() throws IOException {
 863                 zf.close();
 864             }
 865         }
 866     }
 867 
 868     /**
 869      * Closes the ZIP file.
 870      *
 871      * <p> Closing this ZIP file will close all of the input streams
 872      * previously returned by invocations of the {@link #getInputStream
 873      * getInputStream} method.
 874      *
 875      * @throws IOException if an I/O error has occurred
 876      */
 877     public void close() throws IOException {
 878         if (closeRequested) {
 879             return;
 880         }
 881         closeRequested = true;
 882 
 883         synchronized (this) {
 884             // Close streams, release their inflaters, release cached inflaters
 885             // and release zip source
 886             try {
 887                 res.clean();
 888             } catch (UncheckedIOException ioe) {
 889                 throw ioe.getCause();
 890             }
 891         }
 892     }
 893 
 894     /**
 895      * Ensures that the system resources held by this ZipFile object are
 896      * released when there are no more references to it.
 897      *
 898      * @deprecated The {@code finalize} method has been deprecated and will be
 899      *     removed. It is implemented as a no-op. Subclasses that override
 900      *     {@code finalize} in order to perform cleanup should be modified to
 901      *     use alternative cleanup mechanisms and to remove the overriding
 902      *     {@code finalize} method. The recommended cleanup for ZipFile object
 903      *     is to explicitly invoke {@code close} method when it is no longer in
 904      *     use, or use try-with-resources. If the {@code close} is not invoked
 905      *     explicitly the resources held by this object will be released when
 906      *     the instance becomes unreachable.
 907      *
 908      * @throws IOException if an I/O error has occurred
 909      */
 910     @Deprecated(since="9", forRemoval=true)
 911     protected void finalize() throws IOException {}
 912 
 913     private void ensureOpen() {
 914         if (closeRequested) {
 915             throw new IllegalStateException("zip file closed");
 916         }
 917         if (res.zsrc == null) {
 918             throw new IllegalStateException("The object is not initialized.");
 919         }
 920     }
 921 
 922     private void ensureOpenOrZipException() throws IOException {
 923         if (closeRequested) {
 924             throw new ZipException("ZipFile closed");
 925         }
 926     }
 927 
 928     /*
 929      * Inner class implementing the input stream used to read a
 930      * (possibly compressed) zip file entry.
 931      */
 932    private class ZipFileInputStream extends InputStream {
 933         private volatile boolean closeRequested;
 934         private   long pos;     // current position within entry data
 935         protected long rem;     // number of remaining bytes within entry
 936         protected long size;    // uncompressed size of this entry
 937 
 938         ZipFileInputStream(byte[] cen, int cenpos) {
 939             rem = CENSIZ(cen, cenpos);
 940             size = CENLEN(cen, cenpos);
 941             pos = CENOFF(cen, cenpos);
 942             // zip64
 943             if (rem == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL ||
 944                 pos == ZIP64_MAGICVAL) {
 945                 checkZIP64(cen, cenpos);
 946             }
 947             // negative for lazy initialization, see getDataOffset();
 948             pos = - (pos + ZipFile.this.res.zsrc.locpos);
 949         }
 950 
 951          private void checkZIP64(byte[] cen, int cenpos) {
 952             int off = cenpos + CENHDR + CENNAM(cen, cenpos);
 953             int end = off + CENEXT(cen, cenpos);
 954             while (off + 4 < end) {
 955                 int tag = get16(cen, off);
 956                 int sz = get16(cen, off + 2);
 957                 off += 4;
 958                 if (off + sz > end)         // invalid data
 959                     break;
 960                 if (tag == EXTID_ZIP64) {
 961                     if (size == ZIP64_MAGICVAL) {
 962                         if (sz < 8 || (off + 8) > end)
 963                             break;
 964                         size = get64(cen, off);
 965                         sz -= 8;
 966                         off += 8;
 967                     }
 968                     if (rem == ZIP64_MAGICVAL) {
 969                         if (sz < 8 || (off + 8) > end)
 970                             break;
 971                         rem = get64(cen, off);
 972                         sz -= 8;
 973                         off += 8;
 974                     }
 975                     if (pos == ZIP64_MAGICVAL) {
 976                         if (sz < 8 || (off + 8) > end)
 977                             break;
 978                         pos = get64(cen, off);
 979                         sz -= 8;
 980                         off += 8;
 981                     }
 982                     break;
 983                 }
 984                 off += sz;
 985             }
 986         }
 987 
 988        /* The Zip file spec explicitly allows the LOC extra data size to
 989         * be different from the CEN extra data size. Since we cannot trust
 990         * the CEN extra data size, we need to read the LOC to determine
 991         * the entry data offset.
 992         */
 993         private long initDataOffset() throws IOException {
 994             if (pos <= 0) {
 995                 byte[] loc = new byte[LOCHDR];
 996                 pos = -pos;
 997                 int len = ZipFile.this.res.zsrc.readFullyAt(loc, 0, loc.length, pos);
 998                 if (len != LOCHDR) {
 999                     throw new ZipException("ZipFile error reading zip file");
1000                 }
1001                 if (LOCSIG(loc) != LOCSIG) {
1002                     throw new ZipException("ZipFile invalid LOC header (bad signature)");
1003                 }
1004                 pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc);
1005             }
1006             return pos;
1007         }
1008 
1009         public int read(byte b[], int off, int len) throws IOException {
1010             synchronized (ZipFile.this) {
1011                 ensureOpenOrZipException();
1012                 initDataOffset();
1013                 if (rem == 0) {
1014                     return -1;
1015                 }
1016                 if (len > rem) {
1017                     len = (int) rem;
1018                 }
1019                 if (len <= 0) {
1020                     return 0;
1021                 }
1022                 len = ZipFile.this.res.zsrc.readAt(b, off, len, pos);
1023                 if (len > 0) {
1024                     pos += len;
1025                     rem -= len;
1026                 }
1027             }
1028             if (rem == 0) {
1029                 close();
1030             }
1031             return len;
1032         }
1033 
1034         public int read() throws IOException {
1035             byte[] b = new byte[1];
1036             if (read(b, 0, 1) == 1) {
1037                 return b[0] & 0xff;
1038             } else {
1039                 return -1;
1040             }
1041         }
1042 
1043         public long skip(long n) throws IOException {
1044             synchronized (ZipFile.this) {
1045                 initDataOffset();
1046                 if (n > rem) {
1047                     n = rem;
1048                 }
1049                 pos += n;
1050                 rem -= n;
1051             }
1052             if (rem == 0) {
1053                 close();
1054             }
1055             return n;
1056         }
1057 
1058         public int available() {
1059             return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
1060         }
1061 
1062         public long size() {
1063             return size;
1064         }
1065 
1066         public void close() {
1067             if (closeRequested) {
1068                 return;
1069             }
1070             closeRequested = true;
1071             rem = 0;
1072             synchronized (res.istreams) {
1073                 res.istreams.remove(this);
1074             }
1075         }
1076 
1077     }
1078 
1079     /**
1080      * Returns the names of all non-directory entries that begin with
1081      * "META-INF/" (case ignored). This method is used in JarFile, via
1082      * SharedSecrets, as an optimization when looking up manifest and
1083      * signature file entries. Returns null if no entries were found.
1084      */
1085     private String[] getMetaInfEntryNames() {
1086         synchronized (this) {
1087             ensureOpen();
1088             Source zsrc = res.zsrc;
1089             if (zsrc.metanames == null) {
1090                 return null;
1091             }
1092             String[] names = new String[zsrc.metanames.length];
1093             byte[] cen = zsrc.cen;
1094             for (int i = 0; i < names.length; i++) {
1095                 int pos = zsrc.metanames[i];
1096                 names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos),
1097                                       StandardCharsets.UTF_8);
1098             }
1099             return names;
1100         }
1101     }
1102 
1103     private static boolean isWindows;
1104     static {
1105         SharedSecrets.setJavaUtilZipFileAccess(
1106             new JavaUtilZipFileAccess() {
1107                 @Override
1108                 public boolean startsWithLocHeader(ZipFile zip) {
1109                     return zip.res.zsrc.startsWithLoc;
1110                 }
1111                 @Override
1112                 public String[] getMetaInfEntryNames(ZipFile zip) {
1113                     return zip.getMetaInfEntryNames();
1114                 }
1115                 @Override
1116                 public JarEntry getEntry(ZipFile zip, String name,
1117                     Function<String, JarEntry> func) {
1118                     return (JarEntry)zip.getEntry(name, func);
1119                 }
1120                 @Override
1121                 public Enumeration<JarEntry> entries(ZipFile zip,
1122                     Function<String, JarEntry> func) {
1123                     return zip.entries(func);
1124                 }
1125                 @Override
1126                 public Stream<JarEntry> stream(ZipFile zip,
1127                     Function<String, JarEntry> func) {
1128                     return zip.stream(func);
1129                 }
1130                 @Override
1131                 public Stream<String> entryNameStream(ZipFile zip) {
1132                     return zip.entryNameStream();
1133                 }
1134              }
1135         );
1136         isWindows = VM.getSavedProperty("os.name").contains("Windows");
1137     }
1138 
1139     private static class Source {
1140         private final Key key;               // the key in files
1141         private int refs = 1;
1142 
1143         private RandomAccessFile zfile;      // zfile of the underlying zip file
1144         private byte[] cen;                  // CEN & ENDHDR
1145         private long locpos;                 // position of first LOC header (usually 0)
1146         private byte[] comment;              // zip file comment
1147                                              // list of meta entries in META-INF dir
1148         private int[] metanames;
1149         private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)
1150 
1151         // A Hashmap for all entries.
1152         //
1153         // A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR,
1154         // We might have a lot of these in a typical system. In order to save space we don't
1155         // keep the name in memory, but merely remember a 32 bit {@code hash} value of the
1156         // entry name and its offset {@code pos} in the central directory hdeader.
1157         //
1158         // private static class Entry {
1159         //     int hash;       // 32 bit hashcode on name
1160         //     int next;       // hash chain: index into entries
1161         //     int pos;        // Offset of central directory file header
1162         // }
1163         // private Entry[] entries;             // array of hashed cen entry
1164         //
1165         // To reduce the total size of entries further, we use a int[] here to store 3 "int"
1166         // {@code hash}, {@code next and {@code "pos for each entry. The entry can then be
1167         // referred by their index of their positions in the {@code entries}.
1168         //
1169         private int[] entries;                  // array of hashed cen entry
1170         private int addEntry(int index, int hash, int next, int pos) {
1171             entries[index++] = hash;
1172             entries[index++] = next;
1173             entries[index++] = pos;
1174             return index;
1175         }
1176         private int getEntryHash(int index) { return entries[index]; }
1177         private int getEntryNext(int index) { return entries[index + 1]; }
1178         private int getEntryPos(int index)  { return entries[index + 2]; }
1179         private static final int ZIP_ENDCHAIN  = -1;
1180         private int total;                   // total number of entries
1181         private int[] table;                 // Hash chain heads: indexes into entries
1182         private int tablelen;                // number of hash heads
1183 
1184         private static class Key {
1185             BasicFileAttributes attrs;
1186             File file;
1187 
1188             public Key(File file, BasicFileAttributes attrs) {
1189                 this.attrs = attrs;
1190                 this.file = file;
1191             }
1192 
1193             public int hashCode() {
1194                 long t = attrs.lastModifiedTime().toMillis();
1195                 return ((int)(t ^ (t >>> 32))) + file.hashCode();
1196             }
1197 
1198             public boolean equals(Object obj) {
1199                 if (obj instanceof Key) {
1200                     Key key = (Key)obj;
1201                     if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) {
1202                         return false;
1203                     }
1204                     Object fk = attrs.fileKey();
1205                     if (fk != null) {
1206                         return  fk.equals(key.attrs.fileKey());
1207                     } else {
1208                         return file.equals(key.file);
1209                     }
1210                 }
1211                 return false;
1212             }
1213         }
1214         private static final HashMap<Key, Source> files = new HashMap<>();
1215 
1216 
1217         static Source get(File file, boolean toDelete) throws IOException {
1218             Key key = new Key(file,
1219                               Files.readAttributes(file.toPath(), BasicFileAttributes.class));
1220             Source src;
1221             synchronized (files) {
1222                 src = files.get(key);
1223                 if (src != null) {
1224                     src.refs++;
1225                     return src;
1226                 }
1227             }
1228             src = new Source(key, toDelete);
1229 
1230             synchronized (files) {
1231                 if (files.containsKey(key)) {    // someone else put in first
1232                     src.close();                 // close the newly created one
1233                     src = files.get(key);
1234                     src.refs++;
1235                     return src;
1236                 }
1237                 files.put(key, src);
1238                 return src;
1239             }
1240         }
1241 
1242         static void release(Source src) throws IOException {
1243             synchronized (files) {
1244                 if (src != null && --src.refs == 0) {
1245                     files.remove(src.key);
1246                     src.close();
1247                 }
1248             }
1249         }
1250 
1251         private Source(Key key, boolean toDelete) throws IOException {
1252             this.key = key;
1253             if (toDelete) {
1254                 if (isWindows) {
1255                     this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess()
1256                                               .openAndDelete(key.file, "r");
1257                 } else {
1258                     this.zfile = new RandomAccessFile(key.file, "r");
1259                     key.file.delete();
1260                 }
1261             } else {
1262                 this.zfile = new RandomAccessFile(key.file, "r");
1263             }
1264             try {
1265                 initCEN(-1);
1266                 byte[] buf = new byte[4];
1267                 readFullyAt(buf, 0, 4, 0);
1268                 this.startsWithLoc = (LOCSIG(buf) == LOCSIG);
1269             } catch (IOException x) {
1270                 try {
1271                     this.zfile.close();
1272                 } catch (IOException xx) {}
1273                 throw x;
1274             }
1275         }
1276 
1277         private void close() throws IOException {
1278             zfile.close();
1279             zfile = null;
1280             cen = null;
1281             entries = null;
1282             table = null;
1283             metanames = null;
1284         }
1285 
1286         private static final int BUF_SIZE = 8192;
1287         private final int readFullyAt(byte[] buf, int off, int len, long pos)
1288             throws IOException
1289         {
1290             synchronized(zfile) {
1291                 zfile.seek(pos);
1292                 int N = len;
1293                 while (N > 0) {
1294                     int n = Math.min(BUF_SIZE, N);
1295                     zfile.readFully(buf, off, n);
1296                     off += n;
1297                     N -= n;
1298                 }
1299                 return len;
1300             }
1301         }
1302 
1303         private final int readAt(byte[] buf, int off, int len, long pos)
1304             throws IOException
1305         {
1306             synchronized(zfile) {
1307                 zfile.seek(pos);
1308                 return zfile.read(buf, off, len);
1309             }
1310         }
1311 
1312         private static final int hashN(byte[] a, int off, int len) {
1313             int h = 1;
1314             while (len-- > 0) {
1315                 h = 31 * h + a[off++];
1316             }
1317             return h;
1318         }
1319 
1320         private static final int hash_append(int hash, byte b) {
1321             return hash * 31 + b;
1322         }
1323 
1324         private static class End {
1325             int  centot;     // 4 bytes
1326             long cenlen;     // 4 bytes
1327             long cenoff;     // 4 bytes
1328             long endpos;     // 4 bytes
1329         }
1330 
1331         /*
1332          * Searches for end of central directory (END) header. The contents of
1333          * the END header will be read and placed in endbuf. Returns the file
1334          * position of the END header, otherwise returns -1 if the END header
1335          * was not found or an error occurred.
1336          */
1337         private End findEND() throws IOException {
1338             long ziplen = zfile.length();
1339             if (ziplen <= 0)
1340                 zerror("zip file is empty");
1341             End end = new End();
1342             byte[] buf = new byte[READBLOCKSZ];
1343             long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
1344             long minPos = minHDR - (buf.length - ENDHDR);
1345             for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) {
1346                 int off = 0;
1347                 if (pos < 0) {
1348                     // Pretend there are some NUL bytes before start of file
1349                     off = (int)-pos;
1350                     Arrays.fill(buf, 0, off, (byte)0);
1351                 }
1352                 int len = buf.length - off;
1353                 if (readFullyAt(buf, off, len, pos + off) != len ) {
1354                     zerror("zip END header not found");
1355                 }
1356                 // Now scan the block backwards for END header signature
1357                 for (int i = buf.length - ENDHDR; i >= 0; i--) {
1358                     if (buf[i+0] == (byte)'P'    &&
1359                         buf[i+1] == (byte)'K'    &&
1360                         buf[i+2] == (byte)'\005' &&
1361                         buf[i+3] == (byte)'\006') {
1362                         // Found ENDSIG header
1363                         byte[] endbuf = Arrays.copyOfRange(buf, i, i + ENDHDR);
1364                         end.centot = ENDTOT(endbuf);
1365                         end.cenlen = ENDSIZ(endbuf);
1366                         end.cenoff = ENDOFF(endbuf);
1367                         end.endpos = pos + i;
1368                         int comlen = ENDCOM(endbuf);
1369                         if (end.endpos + ENDHDR + comlen != ziplen) {
1370                             // ENDSIG matched, however the size of file comment in it does
1371                             // not match the real size. One "common" cause for this problem
1372                             // is some "extra" bytes are padded at the end of the zipfile.
1373                             // Let's do some extra verification, we don't care about the
1374                             // performance in this situation.
1375                             byte[] sbuf = new byte[4];
1376                             long cenpos = end.endpos - end.cenlen;
1377                             long locpos = cenpos - end.cenoff;
1378                             if  (cenpos < 0 ||
1379                                  locpos < 0 ||
1380                                  readFullyAt(sbuf, 0, sbuf.length, cenpos) != 4 ||
1381                                  GETSIG(sbuf) != CENSIG ||
1382                                  readFullyAt(sbuf, 0, sbuf.length, locpos) != 4 ||
1383                                  GETSIG(sbuf) != LOCSIG) {
1384                                 continue;
1385                             }
1386                         }
1387                         if (comlen > 0) {    // this zip file has comlen
1388                             comment = new byte[comlen];
1389                             if (readFullyAt(comment, 0, comlen, end.endpos + ENDHDR) != comlen) {
1390                                 zerror("zip comment read failed");
1391                             }
1392                         }
1393                         // must check for a zip64 end record; it is always permitted to be present
1394                         try {
1395                             byte[] loc64 = new byte[ZIP64_LOCHDR];
1396                             if (end.endpos < ZIP64_LOCHDR ||
1397                                 readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
1398                                 != loc64.length || GETSIG(loc64) != ZIP64_LOCSIG) {
1399                                 return end;
1400                             }
1401                             long end64pos = ZIP64_LOCOFF(loc64);
1402                             byte[] end64buf = new byte[ZIP64_ENDHDR];
1403                             if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
1404                                 != end64buf.length || GETSIG(end64buf) != ZIP64_ENDSIG) {
1405                                 return end;
1406                             }
1407                             // end64 candidate found,
1408                             long cenlen64 = ZIP64_ENDSIZ(end64buf);
1409                             long cenoff64 = ZIP64_ENDOFF(end64buf);
1410                             long centot64 = ZIP64_ENDTOT(end64buf);
1411                             // double-check
1412                             if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MAGICVAL ||
1413                                 cenoff64 != end.cenoff && end.cenoff != ZIP64_MAGICVAL ||
1414                                 centot64 != end.centot && end.centot != ZIP64_MAGICCOUNT) {
1415                                 return end;
1416                             }
1417                             // to use the end64 values
1418                             end.cenlen = cenlen64;
1419                             end.cenoff = cenoff64;
1420                             end.centot = (int)centot64; // assume total < 2g
1421                             end.endpos = end64pos;
1422                         } catch (IOException x) {}    // no zip64 loc/end
1423                         return end;
1424                     }
1425                 }
1426             }
1427             zerror("zip END header not found");
1428             return null; //make compiler happy
1429         }
1430 
1431         // Reads zip file central directory.
1432         private void initCEN(int knownTotal) throws IOException {
1433             if (knownTotal == -1) {
1434                 End end = findEND();
1435                 if (end.endpos == 0) {
1436                     locpos = 0;
1437                     total = 0;
1438                     entries  = new int[0];
1439                     cen = null;
1440                     return;         // only END header present
1441                 }
1442                 if (end.cenlen > end.endpos)
1443                     zerror("invalid END header (bad central directory size)");
1444                 long cenpos = end.endpos - end.cenlen;     // position of CEN table
1445                 // Get position of first local file (LOC) header, taking into
1446                 // account that there may be a stub prefixed to the zip file.
1447                 locpos = cenpos - end.cenoff;
1448                 if (locpos < 0) {
1449                     zerror("invalid END header (bad central directory offset)");
1450                 }
1451                 // read in the CEN and END
1452                 cen = new byte[(int)(end.cenlen + ENDHDR)];
1453                 if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
1454                     zerror("read CEN tables failed");
1455                 }
1456                 total = end.centot;
1457             } else {
1458                 total = knownTotal;
1459             }
1460             // hash table for entries
1461             entries  = new int[total * 3];
1462             tablelen = ((total/2) | 1); // Odd -> fewer collisions
1463             table    =  new int[tablelen];
1464             Arrays.fill(table, ZIP_ENDCHAIN);
1465             int idx = 0;
1466             int hash = 0;
1467             int next = -1;
1468 
1469             // list for all meta entries
1470             ArrayList<Integer> metanamesList = null;
1471 
1472             // Iterate through the entries in the central directory
1473             int i = 0;
1474             int hsh = 0;
1475             int pos = 0;
1476             int limit = cen.length - ENDHDR;
1477             while (pos + CENHDR  <= limit) {
1478                 if (i >= total) {
1479                     // This will only happen if the zip file has an incorrect
1480                     // ENDTOT field, which usually means it contains more than
1481                     // 65535 entries.
1482                     initCEN(countCENHeaders(cen, limit));
1483                     return;
1484                 }
1485                 if (CENSIG(cen, pos) != CENSIG)
1486                     zerror("invalid CEN header (bad signature)");
1487                 int method = CENHOW(cen, pos);
1488                 int nlen   = CENNAM(cen, pos);
1489                 int elen   = CENEXT(cen, pos);
1490                 int clen   = CENCOM(cen, pos);
1491                 if ((CENFLG(cen, pos) & 1) != 0)
1492                     zerror("invalid CEN header (encrypted entry)");
1493                 if (method != STORED && method != DEFLATED)
1494                     zerror("invalid CEN header (bad compression method: " + method + ")");
1495                 if (pos + CENHDR + nlen > limit)
1496                     zerror("invalid CEN header (bad header size)");
1497                 // Record the CEN offset and the name hash in our hash cell.
1498                 hash = hashN(cen, pos + CENHDR, nlen);
1499                 hsh = (hash & 0x7fffffff) % tablelen;
1500                 next = table[hsh];
1501                 table[hsh] = idx;
1502                 idx = addEntry(idx, hash, next, pos);
1503                 // Adds name to metanames.
1504                 if (isMetaName(cen, pos + CENHDR, nlen)) {
1505                     if (metanamesList == null)
1506                         metanamesList = new ArrayList<>(4);
1507                     metanamesList.add(pos);
1508                 }
1509                 // skip ext and comment
1510                 pos += (CENHDR + nlen + elen + clen);
1511                 i++;
1512             }
1513             total = i;
1514             if (metanamesList != null) {
1515                 metanames = new int[metanamesList.size()];
1516                 for (int j = 0, len = metanames.length; j < len; j++) {
1517                     metanames[j] = metanamesList.get(j);
1518                 }
1519             }
1520             if (pos + ENDHDR != cen.length) {
1521                 zerror("invalid CEN header (bad header size)");
1522             }
1523         }
1524 
1525         private static void zerror(String msg) throws ZipException {
1526             throw new ZipException(msg);
1527         }
1528 
1529         /*
1530          * Returns the {@code pos} of the zip cen entry corresponding to the
1531          * specified entry name, or -1 if not found.
1532          */
1533         private int getEntryPos(byte[] name, boolean addSlash) {
1534             if (total == 0) {
1535                 return -1;
1536             }
1537             int hsh = hashN(name, 0, name.length);
1538             int idx = table[(hsh & 0x7fffffff) % tablelen];
1539             /*
1540              * This while loop is an optimization where a double lookup
1541              * for name and name+/ is being performed. The name char
1542              * array has enough room at the end to try again with a
1543              * slash appended if the first table lookup does not succeed.
1544              */
1545             while(true) {
1546                 /*
1547                  * Search down the target hash chain for a entry whose
1548                  * 32 bit hash matches the hashed name.
1549                  */
1550                 while (idx != ZIP_ENDCHAIN) {
1551                     if (getEntryHash(idx) == hsh) {
1552                         // The CEN name must match the specfied one
1553                         int pos = getEntryPos(idx);
1554                         if (name.length == CENNAM(cen, pos)) {
1555                             boolean matched = true;
1556                             int nameoff = pos + CENHDR;
1557                             for (int i = 0; i < name.length; i++) {
1558                                 if (name[i] != cen[nameoff++]) {
1559                                     matched = false;
1560                                     break;
1561                                 }
1562                             }
1563                             if (matched) {
1564                                 return pos;
1565                             }
1566                          }
1567                     }
1568                     idx = getEntryNext(idx);
1569                 }
1570                 /* If not addSlash, or slash is already there, we are done */
1571                 if (!addSlash  || name.length == 0 || name[name.length - 1] == '/') {
1572                      return -1;
1573                 }
1574                 /* Add slash and try once more */
1575                 name = Arrays.copyOf(name, name.length + 1);
1576                 name[name.length - 1] = '/';
1577                 hsh = hash_append(hsh, (byte)'/');
1578                 //idx = table[hsh % tablelen];
1579                 idx = table[(hsh & 0x7fffffff) % tablelen];
1580                 addSlash = false;
1581             }
1582         }
1583 
1584         /**
1585          * Returns true if the bytes represent a non-directory name
1586          * beginning with "META-INF/", disregarding ASCII case.
1587          */
1588         private static boolean isMetaName(byte[] name, int off, int len) {
1589             // Use the "oldest ASCII trick in the book"
1590             return len > 9                     // "META-INF/".length()
1591                 && name[off + len - 1] != '/'  // non-directory
1592                 && (name[off++] | 0x20) == 'm'
1593                 && (name[off++] | 0x20) == 'e'
1594                 && (name[off++] | 0x20) == 't'
1595                 && (name[off++] | 0x20) == 'a'
1596                 && (name[off++]       ) == '-'
1597                 && (name[off++] | 0x20) == 'i'
1598                 && (name[off++] | 0x20) == 'n'
1599                 && (name[off++] | 0x20) == 'f'
1600                 && (name[off]         ) == '/';
1601         }
1602 
1603         /**
1604          * Returns the number of CEN headers in a central directory.
1605          * Will not throw, even if the zip file is corrupt.
1606          *
1607          * @param cen copy of the bytes in a zip file's central directory
1608          * @param size number of bytes in central directory
1609          */
1610         private static int countCENHeaders(byte[] cen, int size) {
1611             int count = 0;
1612             for (int p = 0;
1613                  p + CENHDR <= size;
1614                  p += CENHDR + CENNAM(cen, p) + CENEXT(cen, p) + CENCOM(cen, p))
1615                 count++;
1616             return count;
1617         }
1618     }
1619 }