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.EOFException;
  30 import java.io.File;
  31 import java.io.IOException;
  32 import java.io.InputStream;
  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.Files;
  39 import java.nio.file.attribute.BasicFileAttributes;
  40 import java.util.ArrayDeque;
  41 import java.util.ArrayList;
  42 import java.util.Arrays;
  43 import java.util.Collections;
  44 import java.util.Deque;
  45 import java.util.Enumeration;
  46 import java.util.HashMap;
  47 import java.util.Iterator;


  48 import java.util.NoSuchElementException;
  49 import java.util.Objects;
  50 import java.util.Set;
  51 import java.util.Spliterator;
  52 import java.util.Spliterators;
  53 import java.util.WeakHashMap;
  54 import java.util.stream.Stream;
  55 import java.util.stream.StreamSupport;
  56 import jdk.internal.misc.JavaUtilZipFileAccess;
  57 import jdk.internal.misc.SharedSecrets;

  58 import jdk.internal.misc.VM;
  59 import jdk.internal.perf.PerfCounter;
  60 import jdk.internal.ref.CleanerFactory;
  61 

  62 import static java.util.zip.ZipConstants64.*;
  63 import static java.util.zip.ZipUtils.*;
  64 
  65 /**
  66  * This class is used to read entries from a zip file.
  67  *
  68  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
  69  * or method in this class will cause a {@link NullPointerException} to be
  70  * thrown.
  71  *
  72  * <p>
  73  * @apiNote
  74  * In earlier versions, the {@link Object#finalize} method was overridden and
  75  * specified to close the ZipFile object and release its system resource when
  76  * the instance becomes unreachable. The {@code finalize} method is no longer
  77  * defined. The recommended cleanup for ZipFile object is to explicitly invoke
  78  * {@code close} method when it is no longer in use, or use try-with-resources.
  79  *
  80  * @implNote
  81  * The resources held by this object will be released when the instance becomes
  82  * phantom-reachable, if the {@code close} is not invoked explicitly.
  83  * <p>
  84  *
  85  * @author      David Connelly
  86  * @since 1.1
  87  */
  88 public
  89 class ZipFile implements ZipConstants, Closeable {
  90 
  91     private final String name;     // zip file name
  92     private volatile boolean closeRequested;

  93     private ZipCoder zc;
  94 
  95     // The "resource" used by this zip file that needs to be
  96     // cleaned after use.
  97     // a) the input streams that need to be closed
  98     // b) the list of cached Inflater objects
  99     // c) the "native" source of this zip file.
 100     private final CleanableResource res;
 101 
 102     private static final int STORED = ZipEntry.STORED;
 103     private static final int DEFLATED = ZipEntry.DEFLATED;
 104 
 105     /**
 106      * Mode flag to open a zip file for reading.
 107      */
 108     public static final int OPEN_READ = 0x1;
 109 
 110     /**
 111      * Mode flag to open a zip file and mark it for deletion.  The file will be
 112      * deleted some time between the moment that it is opened and the moment
 113      * that it is closed, but its contents will remain accessible via the
 114      * {@code ZipFile} object until either the close method is invoked or the
 115      * virtual machine exits.
 116      */
 117     public static final int OPEN_DELETE = 0x4;
 118 
 119     /**
 120      * Opens a zip file for reading.
 121      *
 122      * <p>First, if there is a security manager, its {@code checkRead}
 123      * method is called with the {@code name} argument as its argument
 124      * to ensure the read is allowed.
 125      *
 126      * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
 127      * decode the entry names and comments.
 128      *
 129      * @param name the name of the zip file
 130      * @throws ZipException if a ZIP format error has occurred
 131      * @throws IOException if an I/O error has occurred
 132      * @throws SecurityException if a security manager exists and its
 133      *         {@code checkRead} method doesn't allow read access to the file.
 134      *
 135      * @see SecurityManager#checkRead(java.lang.String)
 136      */
 137     public ZipFile(String name) throws IOException {
 138         this(new File(name), OPEN_READ);
 139     }
 140 
 141     /**
 142      * Opens a new {@code ZipFile} to read from the specified
 143      * {@code File} object in the specified mode.  The mode argument
 144      * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
 145      *
 146      * <p>First, if there is a security manager, its {@code checkRead}
 147      * method is called with the {@code name} argument as its argument to
 148      * ensure the read is allowed.
 149      *
 150      * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
 151      * decode the entry names and comments
 152      *
 153      * @param file the ZIP file to be opened for reading
 154      * @param mode the mode in which the file is to be opened
 155      * @throws ZipException if a ZIP format error has occurred
 156      * @throws IOException if an I/O error has occurred
 157      * @throws SecurityException if a security manager exists and
 158      *         its {@code checkRead} method
 159      *         doesn't allow read access to the file,
 160      *         or its {@code checkDelete} method doesn't allow deleting
 161      *         the file when the {@code OPEN_DELETE} flag is set.
 162      * @throws IllegalArgumentException if the {@code mode} argument is invalid
 163      * @see SecurityManager#checkRead(java.lang.String)
 164      * @since 1.3
 165      */
 166     public ZipFile(File file, int mode) throws IOException {
 167         this(file, mode, StandardCharsets.UTF_8);
 168     }
 169 
 170     /**
 171      * Opens a ZIP file for reading given the specified File object.
 172      *
 173      * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
 174      * decode the entry names and comments.
 175      *
 176      * @param file the ZIP file to be opened for reading
 177      * @throws ZipException if a ZIP format error has occurred
 178      * @throws IOException if an I/O error has occurred
 179      */
 180     public ZipFile(File file) throws ZipException, IOException {
 181         this(file, OPEN_READ);
 182     }
 183 
 184     /**
 185      * Opens a new {@code ZipFile} to read from the specified
 186      * {@code File} object in the specified mode.  The mode argument
 187      * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
 188      *
 189      * <p>First, if there is a security manager, its {@code checkRead}
 190      * method is called with the {@code name} argument as its argument to
 191      * ensure the read is allowed.
 192      *
 193      * @param file the ZIP file to be opened for reading
 194      * @param mode the mode in which the file is to be opened
 195      * @param charset
 196      *        the {@linkplain java.nio.charset.Charset charset} to
 197      *        be used to decode the ZIP entry name and comment that are not
 198      *        encoded by using UTF-8 encoding (indicated by entry's general
 199      *        purpose flag).
 200      *
 201      * @throws ZipException if a ZIP format error has occurred
 202      * @throws IOException if an I/O error has occurred
 203      *
 204      * @throws SecurityException
 205      *         if a security manager exists and its {@code checkRead}
 206      *         method doesn't allow read access to the file,or its
 207      *         {@code checkDelete} method doesn't allow deleting the
 208      *         file when the {@code OPEN_DELETE} flag is set
 209      *
 210      * @throws IllegalArgumentException if the {@code mode} argument is invalid
 211      *
 212      * @see SecurityManager#checkRead(java.lang.String)
 213      *
 214      * @since 1.7
 215      */
 216     public ZipFile(File file, int mode, Charset charset) throws IOException
 217     {
 218         if (((mode & OPEN_READ) == 0) ||
 219             ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
 220             throw new IllegalArgumentException("Illegal mode: 0x"+
 221                                                Integer.toHexString(mode));
 222         }
 223         String name = file.getPath();
 224         SecurityManager sm = System.getSecurityManager();
 225         if (sm != null) {
 226             sm.checkRead(name);
 227             if ((mode & OPEN_DELETE) != 0) {
 228                 sm.checkDelete(name);
 229             }
 230         }
 231         Objects.requireNonNull(charset, "charset");
 232 
 233         this.zc = ZipCoder.get(charset);
 234         this.name = name;
 235         long t0 = System.nanoTime();
 236 
 237         this.res = new CleanableResource(this, file, mode); 
 238 
 239         PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
 240         PerfCounter.getZipFileCount().increment();
 241     }
 242 
 243     /**
 244      * Opens a zip file for reading.
 245      *
 246      * <p>First, if there is a security manager, its {@code checkRead}
 247      * method is called with the {@code name} argument as its argument
 248      * to ensure the read is allowed.
 249      *
 250      * @param name the name of the zip file
 251      * @param charset
 252      *        the {@linkplain java.nio.charset.Charset charset} to
 253      *        be used to decode the ZIP entry name and comment that are not
 254      *        encoded by using UTF-8 encoding (indicated by entry's general
 255      *        purpose flag).
 256      *
 257      * @throws ZipException if a ZIP format error has occurred
 258      * @throws IOException if an I/O error has occurred
 259      * @throws SecurityException
 260      *         if a security manager exists and its {@code checkRead}
 261      *         method doesn't allow read access to the file
 262      *
 263      * @see SecurityManager#checkRead(java.lang.String)
 264      *
 265      * @since 1.7
 266      */
 267     public ZipFile(String name, Charset charset) throws IOException
 268     {
 269         this(new File(name), OPEN_READ, charset);
 270     }
 271 
 272     /**
 273      * Opens a ZIP file for reading given the specified File object.
 274      *
 275      * @param file the ZIP file to be opened for reading
 276      * @param charset
 277      *        The {@linkplain java.nio.charset.Charset charset} to be
 278      *        used to decode the ZIP entry name and comment (ignored if
 279      *        the <a href="package-summary.html#lang_encoding"> language
 280      *        encoding bit</a> of the ZIP entry's general purpose bit
 281      *        flag is set).
 282      *
 283      * @throws ZipException if a ZIP format error has occurred
 284      * @throws IOException if an I/O error has occurred
 285      *
 286      * @since 1.7
 287      */
 288     public ZipFile(File file, Charset charset) throws IOException
 289     {
 290         this(file, OPEN_READ, charset);
 291     }
 292 
 293     /**
 294      * Returns the zip file comment, or null if none.
 295      *
 296      * @return the comment string for the zip file, or null if none
 297      *
 298      * @throws IllegalStateException if the zip file has been closed
 299      *
 300      * @since 1.7
 301      */
 302     public String getComment() {
 303         synchronized (this) {
 304             ensureOpen();
 305             if (res.zsrc.comment == null) {
 306                 return null;
 307             }
 308             return zc.toString(res.zsrc.comment);
 309         }
 310     }
 311 
 312     /**
 313      * Returns the zip file entry for the specified name, or null
 314      * if not found.
 315      *
 316      * @param name the name of the entry
 317      * @return the zip file entry, or null if not found
 318      * @throws IllegalStateException if the zip file has been closed
 319      */
 320     public ZipEntry getEntry(String name) {
 321         Objects.requireNonNull(name, "name");
 322         synchronized (this) {
 323             ensureOpen();
 324             byte[] bname = zc.getBytes(name);
 325             int pos = res.zsrc.getEntryPos(bname, true);
 326             if (pos != -1) {
 327                 return getZipEntry(name, bname, pos);
 328             }
 329         }
 330         return null;
 331     }
 332 




 333     /**
 334      * Returns an input stream for reading the contents of the specified
 335      * zip file entry.
 336      * <p>
 337      * Closing this ZIP file will, in turn, close all input streams that
 338      * have been returned by invocations of this method.
 339      *
 340      * @param entry the zip file entry
 341      * @return the input stream for reading the contents of the specified
 342      * zip file entry.
 343      * @throws ZipException if a ZIP format error has occurred
 344      * @throws IOException if an I/O error has occurred
 345      * @throws IllegalStateException if the zip file has been closed
 346      */
 347     public InputStream getInputStream(ZipEntry entry) throws IOException {
 348         Objects.requireNonNull(entry, "entry");
 349         int pos = -1;
 350         ZipFileInputStream in = null;
 351         Source zsrc = res.zsrc;
 352         Set<InputStream> istreams = res.istreams;
 353         synchronized (this) {
 354             ensureOpen();
 355             if (Objects.equals(lastEntryName, entry.name)) {
 356                 pos = lastEntryPos;
 357             } else if (!zc.isUTF8() && (entry.flag & EFS) != 0) {
 358                 pos = zsrc.getEntryPos(zc.getBytesUTF8(entry.name), false);
 359             } else {
 360                 pos = zsrc.getEntryPos(zc.getBytes(entry.name), false);
 361             }
 362             if (pos == -1) {
 363                 return null;
 364             }
 365             in = new ZipFileInputStream(zsrc.cen, pos);
 366             switch (CENHOW(zsrc.cen, pos)) {
 367             case STORED:
 368                 synchronized (istreams) {
 369                     istreams.add(in);
 370                 }
 371                 return in;
 372             case DEFLATED:
 373                 // Inflater likes a bit of slack
 374                 // MORE: Compute good size for inflater stream:
 375                 long size = CENLEN(zsrc.cen, pos) + 2;
 376                 if (size > 65536) {
 377                     size = 8192;
 378                 }
 379                 if (size <= 0) {
 380                     size = 4096;
 381                 }
 382                 InputStream is = new ZipFileInflaterInputStream(in, res, (int) size);
 383                 synchronized (istreams) {
 384                     istreams.add(is);

 385                 }
 386                 return is;
 387             default:
 388                 throw new ZipException("invalid compression method");
 389             }
 390         }
 391     }
 392 
 393     private class ZipFileInflaterInputStream extends InflaterInputStream {
 394         private volatile boolean closeRequested;
 395         private boolean eof = false;
 396         private final Cleanable cleanable;
 397 
 398         ZipFileInflaterInputStream(ZipFileInputStream zfin,
 399                                    CleanableResource res, int size) {
 400             this(zfin, res.getInflater(), res, size);
 401         }
 402 
 403         private ZipFileInflaterInputStream(ZipFileInputStream zfin, Inflater inf,
 404                                            CleanableResource res, int size) {
 405             super(zfin, inf, size);
 406             this.cleanable = CleanerFactory
 407                 .cleaner().register(this, () -> res.releaseInflater(inf));
 408         }
 409 
 410         public void close() throws IOException {
 411             if (closeRequested)
 412                 return;
 413             closeRequested = true;
 414             synchronized (res.istreams) {
 415                 res.istreams.remove(this);






 416             }
 417             cleanable.clean();
 418             // do this last as it may throw IOException
 419             super.close();
 420         }
 421 
 422         // Override fill() method to provide an extra "dummy" byte
 423         // at the end of the input stream. This is required when
 424         // using the "nowrap" Inflater option.
 425         protected void fill() throws IOException {
 426             if (eof) {
 427                 throw new EOFException("Unexpected end of ZLIB input stream");
 428             }
 429             len = in.read(buf, 0, buf.length);
 430             if (len == -1) {
 431                 buf[0] = 0;
 432                 len = 1;
 433                 eof = true;
 434             }
 435             inf.setInput(buf, 0, len);
 436         }
 437 
 438         public int available() throws IOException {
 439             if (closeRequested)
 440                 return 0;
 441             long avail = ((ZipFileInputStream)in).size() - inf.getBytesWritten();
 442             return (avail > (long) Integer.MAX_VALUE ?
 443                     Integer.MAX_VALUE : (int) avail);
 444         }





















 445     }
 446 















 447     /**
 448      * Returns the path name of the ZIP file.
 449      * @return the path name of the ZIP file
 450      */
 451     public String getName() {
 452         return name;
 453     }
 454 
 455     private class ZipEntryIterator implements Enumeration<ZipEntry>, Iterator<ZipEntry> {
 456         private int i = 0;
 457         private final int entryCount;
 458 
 459         public ZipEntryIterator() {
 460             synchronized (ZipFile.this) {
 461                 ensureOpen();
 462                 this.entryCount = res.zsrc.total;
 463             }
 464         }
 465 
 466         public boolean hasMoreElements() {
 467             return hasNext();
 468         }
 469 
 470         public boolean hasNext() {
 471             return i < entryCount;
 472         }
 473 
 474         public ZipEntry nextElement() {
 475             return next();
 476         }
 477 
 478         public ZipEntry next() {
 479             synchronized (ZipFile.this) {
 480                 ensureOpen();
 481                 if (!hasNext()) {
 482                     throw new NoSuchElementException();
 483                 }
 484                 // each "entry" has 3 ints in table entries
 485                 return getZipEntry(null, null, res.zsrc.getEntryPos(i++ * 3));
 486             }
 487         }
 488 
 489         public Iterator<ZipEntry> asIterator() {
 490             return this;
 491         }
 492     }
 493 
 494     /**
 495      * Returns an enumeration of the ZIP file entries.
 496      * @return an enumeration of the ZIP file entries
 497      * @throws IllegalStateException if the zip file has been closed
 498      */
 499     public Enumeration<? extends ZipEntry> entries() {
 500         return new ZipEntryIterator();
 501     }
 502 
 503     /**
 504      * Returns an ordered {@code Stream} over the ZIP file entries.
 505      * Entries appear in the {@code Stream} in the order they appear in
 506      * the central directory of the ZIP file.
 507      *
 508      * @return an ordered {@code Stream} of entries in this ZIP file
 509      * @throws IllegalStateException if the zip file has been closed
 510      * @since 1.8
 511      */
 512     public Stream<? extends ZipEntry> stream() {
 513         return StreamSupport.stream(Spliterators.spliterator(
 514                 new ZipEntryIterator(), size(),
 515                 Spliterator.ORDERED | Spliterator.DISTINCT |
 516                         Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
 517     }
 518 
 519     private String lastEntryName;
 520     private int lastEntryPos;
 521 
 522     /* Checks ensureOpen() before invoke this method */
 523     private ZipEntry getZipEntry(String name, byte[] bname, int pos) {
 524         byte[] cen = res.zsrc.cen;
 525         int nlen = CENNAM(cen, pos);
 526         int elen = CENEXT(cen, pos);
 527         int clen = CENCOM(cen, pos);
 528         int flag = CENFLG(cen, pos);
 529         if (name == null || bname.length != nlen) {
 530             // to use the entry name stored in cen, if the passed in name is
 531             // (1) null, invoked from iterator, or
 532             // (2) not equal to the name stored, a slash is appended during
 533             // getEntryPos() search.
 534             if (!zc.isUTF8() && (flag & EFS) != 0) {
 535                 name = zc.toStringUTF8(cen, pos + CENHDR, nlen);
 536             } else {
 537                 name = zc.toString(cen, pos + CENHDR, nlen);
 538             }
 539         }
 540         ZipEntry e = new ZipEntry(name);
 541         e.flag = flag;
 542         e.xdostime = CENTIM(cen, pos);
 543         e.crc = CENCRC(cen, pos);
 544         e.size = CENLEN(cen, pos);
 545         e.csize = CENSIZ(cen, pos);
 546         e.method = CENHOW(cen, pos);
 547         if (elen != 0) {
 548             int start = pos + CENHDR + nlen;
 549             e.setExtra0(Arrays.copyOfRange(cen, start, start + elen), true);
 550         }
 551         if (clen != 0) {
 552             int start = pos + CENHDR + nlen + elen;
 553             if (!zc.isUTF8() && (flag & EFS) != 0) {
 554                 e.comment = zc.toStringUTF8(cen, start, clen);
 555             } else {
 556                 e.comment = zc.toString(cen, start, clen);
 557             }
 558         }
 559         lastEntryName = e.name;
 560         lastEntryPos = pos;
 561         return e;
 562     }
 563 
 564     /**
 565      * Returns the number of entries in the ZIP file.
 566      *
 567      * @return the number of entries in the ZIP file
 568      * @throws IllegalStateException if the zip file has been closed
 569      */
 570     public int size() {
 571         synchronized (this) {
 572             ensureOpen();
 573             return res.zsrc.total;
 574         }
 575     }
 576 
 577     private static class CleanableResource implements Runnable {
 578         private final Cleanable cleanable;
 579 
 580         // The outstanding inputstreams that need to be closed
 581         final Set<InputStream> istreams;
 582 
 583         // List of cached Inflater objects for decompression,
 584         // set to null when closed
 585         private Deque<Inflater> inflaters;
 586 
 587         // zip source
 588         final Source zsrc;
 589 
 590         CleanableResource(ZipFile zf, File file, int mode) throws IOException {
 591             this.cleanable = CleanerFactory.cleaner().register(zf, this);
 592             this.istreams = Collections.newSetFromMap(new WeakHashMap<>());
 593             this.inflaters = new ArrayDeque<>();
 594             this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0);
 595         }

 596 
 597         void clean() throws IOException {
 598             try {
 599                 cleanable.clean();
 600             } catch (UncheckedIOException e) {
 601                 // unwrap UncheckedIOException and re-throw it
 602                 throw e.getCause();
 603             }
 604         }
 605 
 606         Inflater getInflater() {
 607             Deque<Inflater> inflaters = this.inflaters;
 608             if (inflaters != null) {
 609                 synchronized (inflaters) {
 610                     // double checked!
 611                     if (this.inflaters == inflaters) {
 612                         Inflater inf = inflaters.poll();
 613                         if (inf != null) {
 614                             return inf;
 615                         }
 616                     }
 617                 }
 618             }
 619             // inflaters cache already closed or empty - allocate new
 620             return new Inflater(true);
 621         }
 622 
 623         void releaseInflater(Inflater inf) {
 624             Deque<Inflater> inflaters = this.inflaters;
 625             if (inflaters != null) {
 626                 synchronized (inflaters) {
 627                     // double checked!
 628                     if (this.inflaters == inflaters) {
 629                         inf.reset();
 630                         inflaters.add(inf);
 631                         return;
 632                     }
 633                 }
 634             }
 635             // inflaters cache already closed - just end late comers
 636             inf.end();
 637         }
 638 
 639         public void run() {
 640             // Release cached inflaters and close inflaters cache 1st
 641             Deque<Inflater> inflaters = this.inflaters;
 642             if (inflaters != null) {
 643                 synchronized (inflaters) {
 644                     // no need to double-check as only one thread gets a chance
 645                     // to execute run() (Cleaner guarantee)...
 646                     Inflater inf;
 647                     while ((inf = inflaters.poll()) != null) {
 648                         inf.end();
 649                     }
 650                     // close inflaters cache
 651                     this.inflaters = null;
 652                 }
 653             }
 654             // collect IOException(s)...
 655             IOException ioe = null;
 656             // close streams
 657             if (istreams != null) {
 658                 synchronized (istreams) {
 659                     if (!istreams.isEmpty()) {
 660                         InputStream[] copy = istreams.toArray(new InputStream[0]);
 661                         istreams.clear();
 662                         for (InputStream is : copy) {
 663                             try {
 664                                 is.close();
 665                             } catch (IOException e) {
 666                                 if (ioe == null) ioe = e; else ioe.addSuppressed(e);
 667                             }
 668                         }
 669                     }
 670                 }
 671             }
 672             // Release zip src
 673             if (zsrc != null) {
 674                 synchronized (zsrc) {
 675                     try {
 676                         Source.release(zsrc);
 677                     } catch (IOException e) {
 678                         if (ioe == null) ioe = e; else ioe.addSuppressed(e);
 679                     }
 680                 }
 681             }
 682             // throw possible IOException wrapped into unchecked
 683             if (ioe != null) {
 684                 throw new UncheckedIOException(ioe);
 685             }
 686         }
 687     }
 688 
 689     /**
 690      * Closes the ZIP file.
 691      *
 692      * <p> Closing this ZIP file will close all of the input streams
 693      * previously returned by invocations of the {@link #getInputStream
 694      * getInputStream} method.
 695      *















 696      * @throws IOException if an I/O error has occurred

 697      */
 698     public void close() throws IOException {
 699         if (closeRequested) {
 700             return;
 701         }
 702         closeRequested = true;
 703 
 704         synchronized (this) {
 705             // Close streams, release their inflaters, release cached inflaters
 706             // and release zip source
 707             res.clean();
 708         }
 709     }
 710 
 711     private void ensureOpen() {
 712         if (closeRequested) {
 713             throw new IllegalStateException("zip file closed");
 714         }



 715     }
 716 
 717     private void ensureOpenOrZipException() throws IOException {
 718         if (closeRequested) {
 719             throw new ZipException("ZipFile closed");
 720         }
 721     }
 722 
 723     /*
 724      * Inner class implementing the input stream used to read a
 725      * (possibly compressed) zip file entry.
 726      */
 727    private class ZipFileInputStream extends InputStream {
 728         private volatile boolean closeRequested;
 729         private   long pos;     // current position within entry data
 730         protected long rem;     // number of remaining bytes within entry
 731         protected long size;    // uncompressed size of this entry
 732 
 733         ZipFileInputStream(byte[] cen, int cenpos) throws IOException {
 734             rem = CENSIZ(cen, cenpos);
 735             size = CENLEN(cen, cenpos);
 736             pos = CENOFF(cen, cenpos);
 737             // zip64
 738             if (rem == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL ||
 739                 pos == ZIP64_MAGICVAL) {
 740                 checkZIP64(cen, cenpos);
 741             }
 742             // negative for lazy initialization, see getDataOffset();
 743             pos = - (pos + ZipFile.this.res.zsrc.locpos);
 744         }
 745 
 746         private void checkZIP64(byte[] cen, int cenpos) throws IOException {
 747             int off = cenpos + CENHDR + CENNAM(cen, cenpos);
 748             int end = off + CENEXT(cen, cenpos);
 749             while (off + 4 < end) {
 750                 int tag = get16(cen, off);
 751                 int sz = get16(cen, off + 2);
 752                 off += 4;
 753                 if (off + sz > end)         // invalid data
 754                     break;
 755                 if (tag == EXTID_ZIP64) {
 756                     if (size == ZIP64_MAGICVAL) {
 757                         if (sz < 8 || (off + 8) > end)
 758                             break;
 759                         size = get64(cen, off);
 760                         sz -= 8;
 761                         off += 8;
 762                     }
 763                     if (rem == ZIP64_MAGICVAL) {
 764                         if (sz < 8 || (off + 8) > end)
 765                             break;
 766                         rem = get64(cen, off);
 767                         sz -= 8;
 768                         off += 8;
 769                     }
 770                     if (pos == ZIP64_MAGICVAL) {
 771                         if (sz < 8 || (off + 8) > end)
 772                             break;
 773                         pos = get64(cen, off);
 774                         sz -= 8;
 775                         off += 8;
 776                     }
 777                     break;
 778                 }
 779                 off += sz;
 780             }
 781         }
 782 
 783        /* The Zip file spec explicitly allows the LOC extra data size to
 784         * be different from the CEN extra data size. Since we cannot trust
 785         * the CEN extra data size, we need to read the LOC to determine
 786         * the entry data offset.
 787         */
 788         private long initDataOffset() throws IOException {
 789             if (pos <= 0) {
 790                 byte[] loc = new byte[LOCHDR];
 791                 pos = -pos;
 792                 int len = ZipFile.this.res.zsrc.readFullyAt(loc, 0, loc.length, pos);
 793                 if (len != LOCHDR) {
 794                     throw new ZipException("ZipFile error reading zip file");
 795                 }
 796                 if (LOCSIG(loc) != LOCSIG) {
 797                     throw new ZipException("ZipFile invalid LOC header (bad signature)");
 798                 }
 799                 pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc);
 800             }
 801             return pos;
 802         }
 803 
 804         public int read(byte b[], int off, int len) throws IOException {
 805             synchronized (ZipFile.this) {
 806                 ensureOpenOrZipException();
 807                 initDataOffset();
 808                 if (rem == 0) {
 809                     return -1;
 810                 }
 811                 if (len > rem) {
 812                     len = (int) rem;
 813                 }
 814                 if (len <= 0) {
 815                     return 0;
 816                 }
 817                 len = ZipFile.this.res.zsrc.readAt(b, off, len, pos);
 818                 if (len > 0) {
 819                     pos += len;
 820                     rem -= len;
 821                 }
 822             }
 823             if (rem == 0) {
 824                 close();
 825             }
 826             return len;
 827         }
 828 
 829         public int read() throws IOException {
 830             byte[] b = new byte[1];
 831             if (read(b, 0, 1) == 1) {
 832                 return b[0] & 0xff;
 833             } else {
 834                 return -1;
 835             }
 836         }
 837 
 838         public long skip(long n) throws IOException {
 839             synchronized (ZipFile.this) {
 840                 ensureOpenOrZipException();
 841                 initDataOffset();
 842                 if (n > rem) {
 843                     n = rem;
 844                 }
 845                 pos += n;
 846                 rem -= n;
 847             }
 848             if (rem == 0) {
 849                 close();
 850             }
 851             return n;
 852         }
 853 
 854         public int available() {
 855             return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
 856         }
 857 
 858         public long size() {
 859             return size;
 860         }
 861 
 862         public void close() {
 863             if (closeRequested) {
 864                 return;
 865             }
 866             closeRequested = true;
 867             rem = 0;
 868             synchronized (res.istreams) {
 869                 res.istreams.remove(this);
 870             }
 871         }
 872 




 873     }
 874 
 875     /**
 876      * Returns the names of all non-directory entries that begin with
 877      * "META-INF/" (case ignored). This method is used in JarFile, via
 878      * SharedSecrets, as an optimization when looking up manifest and
 879      * signature file entries. Returns null if no entries were found.
 880      */
 881     private String[] getMetaInfEntryNames() {
 882         synchronized (this) {
 883             ensureOpen();
 884             Source zsrc = res.zsrc;
 885             if (zsrc.metanames == null) {
 886                 return null;
 887             }
 888             String[] names = new String[zsrc.metanames.length];
 889             byte[] cen = zsrc.cen;
 890             for (int i = 0; i < names.length; i++) {
 891                 int pos = zsrc.metanames[i];
 892                 names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos),
 893                                       StandardCharsets.UTF_8);
 894             }
 895             return names;
 896         }
 897     }
 898 
 899     private static boolean isWindows;
 900     static {
 901         SharedSecrets.setJavaUtilZipFileAccess(
 902             new JavaUtilZipFileAccess() {
 903                 public boolean startsWithLocHeader(ZipFile zip) {
 904                     return zip.res.zsrc.startsWithLoc;
 905                 }
 906                 public String[] getMetaInfEntryNames(ZipFile zip) {
 907                     return zip.getMetaInfEntryNames();
 908                 }
 909              }
 910         );
 911         isWindows = VM.getSavedProperty("os.name").contains("Windows");
 912     }
 913 
 914     private static class Source {
 915         private final Key key;               // the key in files
 916         private int refs = 1;
 917 
 918         private RandomAccessFile zfile;      // zfile of the underlying zip file
 919         private byte[] cen;                  // CEN & ENDHDR
 920         private long locpos;                 // position of first LOC header (usually 0)
 921         private byte[] comment;              // zip file comment
 922                                              // list of meta entries in META-INF dir
 923         private int[] metanames;
 924         private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)
 925 
 926         // A Hashmap for all entries.
 927         //
 928         // A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR,
 929         // We might have a lot of these in a typical system. In order to save space we don't
 930         // keep the name in memory, but merely remember a 32 bit {@code hash} value of the
 931         // entry name and its offset {@code pos} in the central directory hdeader.
 932         //
 933         // private static class Entry {
 934         //     int hash;       // 32 bit hashcode on name
 935         //     int next;       // hash chain: index into entries
 936         //     int pos;        // Offset of central directory file header
 937         // }
 938         // private Entry[] entries;             // array of hashed cen entry
 939         //
 940         // To reduce the total size of entries further, we use a int[] here to store 3 "int"
 941         // {@code hash}, {@code next and {@code "pos for each entry. The entry can then be
 942         // referred by their index of their positions in the {@code entries}.
 943         //
 944         private int[] entries;                  // array of hashed cen entry
 945         private int addEntry(int index, int hash, int next, int pos) {
 946             entries[index++] = hash;
 947             entries[index++] = next;
 948             entries[index++] = pos;
 949             return index;
 950         }
 951         private int getEntryHash(int index) { return entries[index]; }
 952         private int getEntryNext(int index) { return entries[index + 1]; }
 953         private int getEntryPos(int index)  { return entries[index + 2]; }
 954         private static final int ZIP_ENDCHAIN  = -1;
 955         private int total;                   // total number of entries
 956         private int[] table;                 // Hash chain heads: indexes into entries
 957         private int tablelen;                // number of hash heads
 958 
 959         private static class Key {
 960             BasicFileAttributes attrs;
 961             File file;
 962 
 963             public Key(File file, BasicFileAttributes attrs) {
 964                 this.attrs = attrs;
 965                 this.file = file;
 966             }
 967 
 968             public int hashCode() {
 969                 long t = attrs.lastModifiedTime().toMillis();
 970                 return ((int)(t ^ (t >>> 32))) + file.hashCode();
 971             }
 972 
 973             public boolean equals(Object obj) {
 974                 if (obj instanceof Key) {
 975                     Key key = (Key)obj;
 976                     if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) {
 977                         return false;
 978                     }
 979                     Object fk = attrs.fileKey();
 980                     if (fk != null) {
 981                         return  fk.equals(key.attrs.fileKey());
 982                     } else {
 983                         return file.equals(key.file);
 984                     }
 985                 }
 986                 return false;
 987             }
 988         }
 989         private static final HashMap<Key, Source> files = new HashMap<>();
 990 
 991 
 992         static Source get(File file, boolean toDelete) throws IOException {
 993             Key key = new Key(file,
 994                               Files.readAttributes(file.toPath(), BasicFileAttributes.class));
 995             Source src = null;
 996             synchronized (files) {
 997                 src = files.get(key);
 998                 if (src != null) {
 999                     src.refs++;
1000                     return src;
1001                 }
1002             }
1003             src = new Source(key, toDelete);
1004 
1005             synchronized (files) {
1006                 if (files.containsKey(key)) {    // someone else put in first
1007                     src.close();                 // close the newly created one
1008                     src = files.get(key);
1009                     src.refs++;
1010                     return src;
1011                 }
1012                 files.put(key, src);
1013                 return src;
1014             }
1015         }
1016 
1017         static void release(Source src) throws IOException {
1018             synchronized (files) {
1019                 if (src != null && --src.refs == 0) {
1020                     files.remove(src.key);
1021                     src.close();
1022                 }
1023             }
1024         }
1025 
1026         private Source(Key key, boolean toDelete) throws IOException {
1027             this.key = key;
1028             if (toDelete) {
1029                 if (isWindows) {
1030                     this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess()
1031                                               .openAndDelete(key.file, "r");
1032                 } else {
1033                     this.zfile = new RandomAccessFile(key.file, "r");
1034                     key.file.delete();
1035                 }
1036             } else {
1037                 this.zfile = new RandomAccessFile(key.file, "r");
1038             }
1039             try {
1040                 initCEN(-1);
1041                 byte[] buf = new byte[4];
1042                 readFullyAt(buf, 0, 4, 0);
1043                 this.startsWithLoc = (LOCSIG(buf) == LOCSIG);
1044             } catch (IOException x) {
1045                 try {
1046                     this.zfile.close();
1047                 } catch (IOException xx) {}
1048                 throw x;
1049             }
1050         }
1051 
1052         private void close() throws IOException {
1053             zfile.close();
1054             zfile = null;
1055             cen = null;
1056             entries = null;
1057             table = null;
1058             metanames = null;
1059         }
1060 
1061         private static final int BUF_SIZE = 8192;
1062         private final int readFullyAt(byte[] buf, int off, int len, long pos)
1063             throws IOException
1064         {
1065             synchronized(zfile) {
1066                 zfile.seek(pos);
1067                 int N = len;
1068                 while (N > 0) {
1069                     int n = Math.min(BUF_SIZE, N);
1070                     zfile.readFully(buf, off, n);
1071                     off += n;
1072                     N -= n;
1073                 }
1074                 return len;
1075             }
1076         }
1077 
1078         private final int readAt(byte[] buf, int off, int len, long pos)
1079             throws IOException
1080         {
1081             synchronized(zfile) {
1082                 zfile.seek(pos);
1083                 return zfile.read(buf, off, len);
1084             }
1085         }
1086 
1087         private static final int hashN(byte[] a, int off, int len) {
1088             int h = 1;
1089             while (len-- > 0) {
1090                 h = 31 * h + a[off++];
1091             }
1092             return h;
1093         }
1094 
1095         private static final int hash_append(int hash, byte b) {
1096             return hash * 31 + b;
1097         }
1098 
1099         private static class End {
1100             int  centot;     // 4 bytes
1101             long cenlen;     // 4 bytes
1102             long cenoff;     // 4 bytes
1103             long endpos;     // 4 bytes
1104         }
1105 
1106         /*
1107          * Searches for end of central directory (END) header. The contents of
1108          * the END header will be read and placed in endbuf. Returns the file
1109          * position of the END header, otherwise returns -1 if the END header
1110          * was not found or an error occurred.
1111          */
1112         private End findEND() throws IOException {
1113             long ziplen = zfile.length();
1114             if (ziplen <= 0)
1115                 zerror("zip file is empty");
1116             End end = new End();
1117             byte[] buf = new byte[READBLOCKSZ];
1118             long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
1119             long minPos = minHDR - (buf.length - ENDHDR);
1120             for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) {
1121                 int off = 0;
1122                 if (pos < 0) {
1123                     // Pretend there are some NUL bytes before start of file
1124                     off = (int)-pos;
1125                     Arrays.fill(buf, 0, off, (byte)0);
1126                 }
1127                 int len = buf.length - off;
1128                 if (readFullyAt(buf, off, len, pos + off) != len ) {
1129                     zerror("zip END header not found");
1130                 }
1131                 // Now scan the block backwards for END header signature
1132                 for (int i = buf.length - ENDHDR; i >= 0; i--) {
1133                     if (buf[i+0] == (byte)'P'    &&
1134                         buf[i+1] == (byte)'K'    &&
1135                         buf[i+2] == (byte)'\005' &&
1136                         buf[i+3] == (byte)'\006') {
1137                         // Found ENDSIG header
1138                         byte[] endbuf = Arrays.copyOfRange(buf, i, i + ENDHDR);
1139                         end.centot = ENDTOT(endbuf);
1140                         end.cenlen = ENDSIZ(endbuf);
1141                         end.cenoff = ENDOFF(endbuf);
1142                         end.endpos = pos + i;
1143                         int comlen = ENDCOM(endbuf);
1144                         if (end.endpos + ENDHDR + comlen != ziplen) {
1145                             // ENDSIG matched, however the size of file comment in it does
1146                             // not match the real size. One "common" cause for this problem
1147                             // is some "extra" bytes are padded at the end of the zipfile.
1148                             // Let's do some extra verification, we don't care about the
1149                             // performance in this situation.
1150                             byte[] sbuf = new byte[4];
1151                             long cenpos = end.endpos - end.cenlen;
1152                             long locpos = cenpos - end.cenoff;
1153                             if  (cenpos < 0 ||
1154                                  locpos < 0 ||
1155                                  readFullyAt(sbuf, 0, sbuf.length, cenpos) != 4 ||
1156                                  GETSIG(sbuf) != CENSIG ||
1157                                  readFullyAt(sbuf, 0, sbuf.length, locpos) != 4 ||
1158                                  GETSIG(sbuf) != LOCSIG) {
1159                                 continue;
1160                             }
1161                         }
1162                         if (comlen > 0) {    // this zip file has comlen
1163                             comment = new byte[comlen];
1164                             if (readFullyAt(comment, 0, comlen, end.endpos + ENDHDR) != comlen) {
1165                                 zerror("zip comment read failed");
1166                             }
1167                         }
1168                         // must check for a zip64 end record; it is always permitted to be present
1169                         try {
1170                             byte[] loc64 = new byte[ZIP64_LOCHDR];
1171                             if (end.endpos < ZIP64_LOCHDR ||
1172                                 readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
1173                                 != loc64.length || GETSIG(loc64) != ZIP64_LOCSIG) {
1174                                 return end;
1175                             }
1176                             long end64pos = ZIP64_LOCOFF(loc64);
1177                             byte[] end64buf = new byte[ZIP64_ENDHDR];
1178                             if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
1179                                 != end64buf.length || GETSIG(end64buf) != ZIP64_ENDSIG) {
1180                                 return end;
1181                             }
1182                             // end64 candidate found,
1183                             long cenlen64 = ZIP64_ENDSIZ(end64buf);
1184                             long cenoff64 = ZIP64_ENDOFF(end64buf);
1185                             long centot64 = ZIP64_ENDTOT(end64buf);
1186                             // double-check
1187                             if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MAGICVAL ||
1188                                 cenoff64 != end.cenoff && end.cenoff != ZIP64_MAGICVAL ||
1189                                 centot64 != end.centot && end.centot != ZIP64_MAGICCOUNT) {
1190                                 return end;
1191                             }
1192                             // to use the end64 values
1193                             end.cenlen = cenlen64;
1194                             end.cenoff = cenoff64;
1195                             end.centot = (int)centot64; // assume total < 2g
1196                             end.endpos = end64pos;
1197                         } catch (IOException x) {}    // no zip64 loc/end
1198                         return end;
1199                     }
1200                 }
1201             }
1202             zerror("zip END header not found");
1203             return null; //make compiler happy
1204         }
1205 
1206         // Reads zip file central directory.
1207         private void initCEN(int knownTotal) throws IOException {
1208             if (knownTotal == -1) {
1209                 End end = findEND();
1210                 if (end.endpos == 0) {
1211                     locpos = 0;
1212                     total = 0;
1213                     entries  = new int[0];
1214                     cen = null;
1215                     return;         // only END header present
1216                 }
1217                 if (end.cenlen > end.endpos)
1218                     zerror("invalid END header (bad central directory size)");
1219                 long cenpos = end.endpos - end.cenlen;     // position of CEN table
1220                 // Get position of first local file (LOC) header, taking into
1221                 // account that there may be a stub prefixed to the zip file.
1222                 locpos = cenpos - end.cenoff;
1223                 if (locpos < 0) {
1224                     zerror("invalid END header (bad central directory offset)");
1225                 }
1226                 // read in the CEN and END
1227                 cen = new byte[(int)(end.cenlen + ENDHDR)];
1228                 if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
1229                     zerror("read CEN tables failed");
1230                 }
1231                 total = end.centot;
1232             } else {
1233                 total = knownTotal;
1234             }
1235             // hash table for entries
1236             entries  = new int[total * 3];
1237             tablelen = ((total/2) | 1); // Odd -> fewer collisions
1238             table    =  new int[tablelen];
1239             Arrays.fill(table, ZIP_ENDCHAIN);
1240             int idx = 0;
1241             int hash = 0;
1242             int next = -1;
1243 
1244             // list for all meta entries
1245             ArrayList<Integer> metanamesList = null;
1246 
1247             // Iterate through the entries in the central directory
1248             int i = 0;
1249             int hsh = 0;
1250             int pos = 0;
1251             int limit = cen.length - ENDHDR;
1252             while (pos + CENHDR  <= limit) {
1253                 if (i >= total) {
1254                     // This will only happen if the zip file has an incorrect
1255                     // ENDTOT field, which usually means it contains more than
1256                     // 65535 entries.
1257                     initCEN(countCENHeaders(cen, limit));
1258                     return;
1259                 }
1260                 if (CENSIG(cen, pos) != CENSIG)
1261                     zerror("invalid CEN header (bad signature)");
1262                 int method = CENHOW(cen, pos);
1263                 int nlen   = CENNAM(cen, pos);
1264                 int elen   = CENEXT(cen, pos);
1265                 int clen   = CENCOM(cen, pos);
1266                 if ((CENFLG(cen, pos) & 1) != 0)
1267                     zerror("invalid CEN header (encrypted entry)");
1268                 if (method != STORED && method != DEFLATED)
1269                     zerror("invalid CEN header (bad compression method: " + method + ")");
1270                 if (pos + CENHDR + nlen > limit)
1271                     zerror("invalid CEN header (bad header size)");
1272                 // Record the CEN offset and the name hash in our hash cell.
1273                 hash = hashN(cen, pos + CENHDR, nlen);
1274                 hsh = (hash & 0x7fffffff) % tablelen;
1275                 next = table[hsh];
1276                 table[hsh] = idx;
1277                 idx = addEntry(idx, hash, next, pos);
1278                 // Adds name to metanames.
1279                 if (isMetaName(cen, pos + CENHDR, nlen)) {
1280                     if (metanamesList == null)
1281                         metanamesList = new ArrayList<>(4);
1282                     metanamesList.add(pos);
1283                 }
1284                 // skip ext and comment
1285                 pos += (CENHDR + nlen + elen + clen);
1286                 i++;
1287             }
1288             total = i;
1289             if (metanamesList != null) {
1290                 metanames = new int[metanamesList.size()];
1291                 for (int j = 0, len = metanames.length; j < len; j++) {
1292                     metanames[j] = metanamesList.get(j);
1293                 }
1294             }
1295             if (pos + ENDHDR != cen.length) {
1296                 zerror("invalid CEN header (bad header size)");
1297             }
1298         }
1299 
1300         private static void zerror(String msg) throws ZipException {
1301             throw new ZipException(msg);
1302         }
1303 
1304         /*
1305          * Returns the {@code pos} of the zip cen entry corresponding to the
1306          * specified entry name, or -1 if not found.
1307          */
1308         private int getEntryPos(byte[] name, boolean addSlash) {
1309             if (total == 0) {
1310                 return -1;
1311             }
1312             int hsh = hashN(name, 0, name.length);
1313             int idx = table[(hsh & 0x7fffffff) % tablelen];
1314             /*
1315              * This while loop is an optimization where a double lookup
1316              * for name and name+/ is being performed. The name char
1317              * array has enough room at the end to try again with a
1318              * slash appended if the first table lookup does not succeed.
1319              */
1320             while(true) {
1321                 /*
1322                  * Search down the target hash chain for a entry whose
1323                  * 32 bit hash matches the hashed name.
1324                  */
1325                 while (idx != ZIP_ENDCHAIN) {
1326                     if (getEntryHash(idx) == hsh) {
1327                         // The CEN name must match the specfied one
1328                         int pos = getEntryPos(idx);
1329                         if (name.length == CENNAM(cen, pos)) {
1330                             boolean matched = true;
1331                             int nameoff = pos + CENHDR;
1332                             for (int i = 0; i < name.length; i++) {
1333                                 if (name[i] != cen[nameoff++]) {
1334                                     matched = false;
1335                                     break;
1336                                 }
1337                             }
1338                             if (matched) {
1339                                 return pos;
1340                             }
1341                          }
1342                     }
1343                     idx = getEntryNext(idx);
1344                 }
1345                 /* If not addSlash, or slash is already there, we are done */
1346                 if (!addSlash  || name.length == 0 || name[name.length - 1] == '/') {
1347                      return -1;
1348                 }
1349                 /* Add slash and try once more */
1350                 name = Arrays.copyOf(name, name.length + 1);
1351                 name[name.length - 1] = '/';
1352                 hsh = hash_append(hsh, (byte)'/');
1353                 //idx = table[hsh % tablelen];
1354                 idx = table[(hsh & 0x7fffffff) % tablelen];
1355                 addSlash = false;
1356             }
1357         }
1358 
1359         /**
1360          * Returns true if the bytes represent a non-directory name
1361          * beginning with "META-INF/", disregarding ASCII case.
1362          */
1363         private static boolean isMetaName(byte[] name, int off, int len) {
1364             // Use the "oldest ASCII trick in the book"
1365             return len > 9                     // "META-INF/".length()
1366                 && name[off + len - 1] != '/'  // non-directory
1367                 && (name[off++] | 0x20) == 'm'
1368                 && (name[off++] | 0x20) == 'e'
1369                 && (name[off++] | 0x20) == 't'
1370                 && (name[off++] | 0x20) == 'a'
1371                 && (name[off++]       ) == '-'
1372                 && (name[off++] | 0x20) == 'i'
1373                 && (name[off++] | 0x20) == 'n'
1374                 && (name[off++] | 0x20) == 'f'
1375                 && (name[off]         ) == '/';
1376         }
1377 
1378         /**
1379          * Returns the number of CEN headers in a central directory.
1380          * Will not throw, even if the zip file is corrupt.
1381          *
1382          * @param cen copy of the bytes in a zip file's central directory
1383          * @param size number of bytes in central directory
1384          */
1385         private static int countCENHeaders(byte[] cen, int size) {
1386             int count = 0;
1387             for (int p = 0;
1388                  p + CENHDR <= size;
1389                  p += CENHDR + CENNAM(cen, p) + CENEXT(cen, p) + CENCOM(cen, p))
1390                 count++;
1391             return count;
1392         }
1393     }
1394 }
--- EOF ---