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