< prev index next >

src/java.base/share/classes/java/util/zip/ZipFile.java

Print this page




   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.nio.charset.Charset;
  35 import java.nio.charset.StandardCharsets;
  36 import java.nio.file.attribute.BasicFileAttributes;
  37 import java.nio.file.Path;
  38 import java.nio.file.Files;
  39 
  40 import java.util.ArrayDeque;
  41 import java.util.ArrayList;
  42 import java.util.Arrays;

  43 import java.util.Deque;
  44 import java.util.Enumeration;
  45 import java.util.HashMap;
  46 import java.util.Iterator;
  47 import java.util.Map;
  48 import java.util.Objects;
  49 import java.util.NoSuchElementException;


  50 import java.util.Spliterator;
  51 import java.util.Spliterators;
  52 import java.util.WeakHashMap;
  53 import java.util.stream.Stream;
  54 import java.util.stream.StreamSupport;
  55 import jdk.internal.misc.JavaUtilZipFileAccess;
  56 import jdk.internal.misc.SharedSecrets;
  57 import jdk.internal.misc.JavaIORandomAccessFileAccess;
  58 import jdk.internal.misc.VM;
  59 import jdk.internal.perf.PerfCounter;

  60 
  61 import static java.util.zip.ZipConstants.*;
  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  * @author      David Connelly
  73  * @since 1.1
  74  */
  75 public
  76 class ZipFile implements ZipConstants, Closeable {
  77 
  78     private final String name;     // zip file name
  79     private volatile boolean closeRequested;
  80     private Source zsrc;
  81     private ZipCoder zc;
  82 







  83     private static final int STORED = ZipEntry.STORED;
  84     private static final int DEFLATED = ZipEntry.DEFLATED;
  85 
  86     /**
  87      * Mode flag to open a zip file for reading.
  88      */
  89     public static final int OPEN_READ = 0x1;
  90 
  91     /**
  92      * Mode flag to open a zip file and mark it for deletion.  The file will be
  93      * deleted some time between the moment that it is opened and the moment
  94      * that it is closed, but its contents will remain accessible via the
  95      * {@code ZipFile} object until either the close method is invoked or the
  96      * virtual machine exits.
  97      */
  98     public static final int OPEN_DELETE = 0x4;
  99 
 100     /**
 101      * Opens a zip file for reading.
 102      *


 193      * @see SecurityManager#checkRead(java.lang.String)
 194      *
 195      * @since 1.7
 196      */
 197     public ZipFile(File file, int mode, Charset charset) throws IOException
 198     {
 199         if (((mode & OPEN_READ) == 0) ||
 200             ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
 201             throw new IllegalArgumentException("Illegal mode: 0x"+
 202                                                Integer.toHexString(mode));
 203         }
 204         String name = file.getPath();
 205         SecurityManager sm = System.getSecurityManager();
 206         if (sm != null) {
 207             sm.checkRead(name);
 208             if ((mode & OPEN_DELETE) != 0) {
 209                 sm.checkDelete(name);
 210             }
 211         }
 212         Objects.requireNonNull(charset, "charset");

 213         this.zc = ZipCoder.get(charset);
 214         this.name = name;
 215         long t0 = System.nanoTime();
 216         this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0);


 217         PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
 218         PerfCounter.getZipFileCount().increment();
 219     }
 220 
 221     /**
 222      * Opens a zip file for reading.
 223      *
 224      * <p>First, if there is a security manager, its {@code checkRead}
 225      * method is called with the {@code name} argument as its argument
 226      * to ensure the read is allowed.
 227      *
 228      * @param name the name of the zip file
 229      * @param charset
 230      *        the {@linkplain java.nio.charset.Charset charset} to
 231      *        be used to decode the ZIP entry name and comment that are not
 232      *        encoded by using UTF-8 encoding (indicated by entry's general
 233      *        purpose flag).
 234      *
 235      * @throws ZipException if a ZIP format error has occurred
 236      * @throws IOException if an I/O error has occurred


 263      *
 264      * @since 1.7
 265      */
 266     public ZipFile(File file, Charset charset) throws IOException
 267     {
 268         this(file, OPEN_READ, charset);
 269     }
 270 
 271     /**
 272      * Returns the zip file comment, or null if none.
 273      *
 274      * @return the comment string for the zip file, or null if none
 275      *
 276      * @throws IllegalStateException if the zip file has been closed
 277      *
 278      * @since 1.7
 279      */
 280     public String getComment() {
 281         synchronized (this) {
 282             ensureOpen();
 283             if (zsrc.comment == null) {
 284                 return null;
 285             }
 286             return zc.toString(zsrc.comment);
 287         }
 288     }
 289 
 290     /**
 291      * Returns the zip file entry for the specified name, or null
 292      * if not found.
 293      *
 294      * @param name the name of the entry
 295      * @return the zip file entry, or null if not found
 296      * @throws IllegalStateException if the zip file has been closed
 297      */
 298     public ZipEntry getEntry(String name) {
 299         Objects.requireNonNull(name, "name");
 300         synchronized (this) {
 301             ensureOpen();
 302             byte[] bname = zc.getBytes(name);
 303             int pos = zsrc.getEntryPos(bname, true);
 304             if (pos != -1) {
 305                 return getZipEntry(name, bname, pos);
 306             }
 307         }
 308         return null;
 309     }
 310 
 311     // The outstanding inputstreams that need to be closed,
 312     // mapped to the inflater objects they use.
 313     private final Map<InputStream, Inflater> streams = new WeakHashMap<>();
 314 
 315     /**
 316      * Returns an input stream for reading the contents of the specified
 317      * zip file entry.
 318      * <p>
 319      * Closing this ZIP file will, in turn, close all input streams that
 320      * have been returned by invocations of this method.
 321      *
 322      * @param entry the zip file entry
 323      * @return the input stream for reading the contents of the specified
 324      * zip file entry.
 325      * @throws ZipException if a ZIP format error has occurred
 326      * @throws IOException if an I/O error has occurred
 327      * @throws IllegalStateException if the zip file has been closed
 328      */
 329     public InputStream getInputStream(ZipEntry entry) throws IOException {
 330         Objects.requireNonNull(entry, "entry");
 331         int pos = -1;
 332         ZipFileInputStream in = null;


 333         synchronized (this) {
 334             ensureOpen();
 335             if (Objects.equals(lastEntryName, entry.name)) {
 336                 pos = lastEntryPos;
 337             } else if (!zc.isUTF8() && (entry.flag & EFS) != 0) {
 338                 pos = zsrc.getEntryPos(zc.getBytesUTF8(entry.name), false);
 339             } else {
 340                 pos = zsrc.getEntryPos(zc.getBytes(entry.name), false);
 341             }
 342             if (pos == -1) {
 343                 return null;
 344             }
 345             in = new ZipFileInputStream(zsrc.cen, pos);
 346             switch (CENHOW(zsrc.cen, pos)) {
 347             case STORED:
 348                 synchronized (streams) {
 349                     streams.put(in, null);
 350                 }
 351                 return in;
 352             case DEFLATED:
 353                 // Inflater likes a bit of slack
 354                 // MORE: Compute good size for inflater stream:
 355                 long size = CENLEN(zsrc.cen, pos) + 2;
 356                 if (size > 65536) {
 357                     size = 8192;
 358                 }
 359                 if (size <= 0) {
 360                     size = 4096;
 361                 }
 362                 Inflater inf = getInflater();
 363                 InputStream is = new ZipFileInflaterInputStream(in, inf, (int)size);
 364                 synchronized (streams) {
 365                     streams.put(is, inf);
 366                 }
 367                 return is;
 368             default:
 369                 throw new ZipException("invalid compression method");
 370             }
 371         }
 372     }
 373 
 374     private class ZipFileInflaterInputStream extends InflaterInputStream {
 375         private volatile boolean closeRequested;
 376         private boolean eof = false;
 377         private final ZipFileInputStream zfin;
 378 
 379         ZipFileInflaterInputStream(ZipFileInputStream zfin, Inflater inf,
 380                 int size) {





 381             super(zfin, inf, size);
 382             this.zfin = zfin;

 383         }
 384 
 385         public void close() throws IOException {
 386             if (closeRequested)
 387                 return;
 388             closeRequested = true;
 389 
 390             super.close();
 391             Inflater inf;
 392             synchronized (streams) {
 393                 inf = streams.remove(this);
 394             }
 395             if (inf != null) {
 396                 releaseInflater(inf);
 397             }



 398         }
 399 
 400         // Override fill() method to provide an extra "dummy" byte
 401         // at the end of the input stream. This is required when
 402         // using the "nowrap" Inflater option.
 403         protected void fill() throws IOException {
 404             if (eof) {
 405                 throw new EOFException("Unexpected end of ZLIB input stream");
 406             }
 407             len = in.read(buf, 0, buf.length);
 408             if (len == -1) {
 409                 buf[0] = 0;
 410                 len = 1;
 411                 eof = true;
 412             }
 413             inf.setInput(buf, 0, len);
 414         }
 415 
 416         public int available() throws IOException {
 417             if (closeRequested)
 418                 return 0;
 419             long avail = zfin.size() - inf.getBytesWritten();
 420             return (avail > (long) Integer.MAX_VALUE ?
 421                     Integer.MAX_VALUE : (int) avail);
 422         }
 423 
 424         @SuppressWarnings("deprecation")
 425         protected void finalize() throws Throwable {
 426             close();
 427         }
 428     }
 429 
 430     /*
 431      * Gets an inflater from the list of available inflaters or allocates
 432      * a new one.
 433      */
 434     private Inflater getInflater() {
 435         Inflater inf;
 436         synchronized (inflaterCache) {
 437             while ((inf = inflaterCache.poll()) != null) {
 438                 if (!inf.ended()) {
 439                     return inf;
 440                 }
 441             }
 442         }
 443         return new Inflater(true);
 444     }
 445 
 446     /*
 447      * Releases the specified inflater to the list of available inflaters.
 448      */
 449     private void releaseInflater(Inflater inf) {
 450         if (!inf.ended()) {
 451             inf.reset();
 452             synchronized (inflaterCache) {
 453                 inflaterCache.add(inf);
 454             }
 455         }
 456     }
 457 
 458     // List of available Inflater objects for decompression
 459     private final Deque<Inflater> inflaterCache = new ArrayDeque<>();
 460 
 461     /**
 462      * Returns the path name of the ZIP file.
 463      * @return the path name of the ZIP file
 464      */
 465     public String getName() {
 466         return name;
 467     }
 468 
 469     private class ZipEntryIterator implements Enumeration<ZipEntry>, Iterator<ZipEntry> {
 470         private int i = 0;
 471         private final int entryCount;
 472 
 473         public ZipEntryIterator() {
 474             synchronized (ZipFile.this) {
 475                 ensureOpen();
 476                 this.entryCount = zsrc.total;
 477             }
 478         }
 479 
 480         public boolean hasMoreElements() {
 481             return hasNext();
 482         }
 483 
 484         public boolean hasNext() {
 485             return i < entryCount;
 486         }
 487 
 488         public ZipEntry nextElement() {
 489             return next();
 490         }
 491 
 492         public ZipEntry next() {
 493             synchronized (ZipFile.this) {
 494                 ensureOpen();
 495                 if (!hasNext()) {
 496                     throw new NoSuchElementException();
 497                 }
 498                 // each "entry" has 3 ints in table entries
 499                 return getZipEntry(null, null, zsrc.getEntryPos(i++ * 3));
 500             }
 501         }
 502 
 503         public Iterator<ZipEntry> asIterator() {
 504             return this;
 505         }
 506     }
 507 
 508     /**
 509      * Returns an enumeration of the ZIP file entries.
 510      * @return an enumeration of the ZIP file entries
 511      * @throws IllegalStateException if the zip file has been closed
 512      */
 513     public Enumeration<? extends ZipEntry> entries() {
 514         return new ZipEntryIterator();
 515     }
 516 
 517     /**
 518      * Returns an ordered {@code Stream} over the ZIP file entries.
 519      * Entries appear in the {@code Stream} in the order they appear in
 520      * the central directory of the ZIP file.
 521      *
 522      * @return an ordered {@code Stream} of entries in this ZIP file
 523      * @throws IllegalStateException if the zip file has been closed
 524      * @since 1.8
 525      */
 526     public Stream<? extends ZipEntry> stream() {
 527         return StreamSupport.stream(Spliterators.spliterator(
 528                 new ZipEntryIterator(), size(),
 529                 Spliterator.ORDERED | Spliterator.DISTINCT |
 530                         Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
 531     }
 532 
 533     private String lastEntryName;
 534     private int lastEntryPos;
 535 
 536     /* Checks ensureOpen() before invoke this method */
 537     private ZipEntry getZipEntry(String name, byte[] bname, int pos) {
 538         byte[] cen = zsrc.cen;
 539         int nlen = CENNAM(cen, pos);
 540         int elen = CENEXT(cen, pos);
 541         int clen = CENCOM(cen, pos);
 542         int flag = CENFLG(cen, pos);
 543         if (name == null || bname.length != nlen) {
 544             // to use the entry name stored in cen, if the passed in name is
 545             // (1) null, invoked from iterator, or
 546             // (2) not equal to the name stored, a slash is appended during
 547             // getEntryPos() search.
 548             if (!zc.isUTF8() && (flag & EFS) != 0) {
 549                 name = zc.toStringUTF8(cen, pos + CENHDR, nlen);
 550             } else {
 551                 name = zc.toString(cen, pos + CENHDR, nlen);
 552             }
 553         }
 554         ZipEntry e = new ZipEntry(name);
 555         e.flag = flag;
 556         e.xdostime = CENTIM(cen, pos);
 557         e.crc = CENCRC(cen, pos);
 558         e.size = CENLEN(cen, pos);


 567             if (!zc.isUTF8() && (flag & EFS) != 0) {
 568                 e.comment = zc.toStringUTF8(cen, start, clen);
 569             } else {
 570                 e.comment = zc.toString(cen, start, clen);
 571             }
 572         }
 573         lastEntryName = e.name;
 574         lastEntryPos = pos;
 575         return e;
 576     }
 577 
 578     /**
 579      * Returns the number of entries in the ZIP file.
 580      *
 581      * @return the number of entries in the ZIP file
 582      * @throws IllegalStateException if the zip file has been closed
 583      */
 584     public int size() {
 585         synchronized (this) {
 586             ensureOpen();
 587             return zsrc.total;
 588         }
 589     }
 590 
 591     /**
 592      * Closes the ZIP file.
 593      * <p> Closing this ZIP file will close all of the input streams
 594      * previously returned by invocations of the {@link #getInputStream
 595      * getInputStream} method.
 596      *
 597      * @throws IOException if an I/O error has occurred
 598      */
 599     public void close() throws IOException {
 600         if (closeRequested) {
 601             return;







 602         }
 603         closeRequested = true;
 604 
 605         synchronized (this) {
 606             // Close streams, release their inflaters
 607             synchronized (streams) {
 608                 if (!streams.isEmpty()) {
 609                     Map<InputStream, Inflater> copy = new HashMap<>(streams);
 610                     streams.clear();
 611                     for (Map.Entry<InputStream, Inflater> e : copy.entrySet()) {
 612                         e.getKey().close();
 613                         Inflater inf = e.getValue();







 614                         if (inf != null) {
 615                             inf.end();
 616                         }
 617                     }
 618                 }
 619             }
 620             // Release cached inflaters
 621             synchronized (inflaterCache) {

























 622                 Inflater inf;
 623                 while ((inf = inflaterCache.poll()) != null) {
 624                     inf.end();
 625                 }





















 626             }
 627             // Release zip src
 628             if (zsrc != null) {
 629                 Source.close(zsrc);
 630                 zsrc = null;









 631             }
 632         }
 633     }
 634 
 635     /**
 636      * Ensures that the system resources held by this ZipFile object are
 637      * released when there are no more references to it.



 638      *
 639      * <p>
 640      * Since the time when GC would invoke this method is undetermined,
 641      * it is strongly recommended that applications invoke the {@code close}
 642      * method as soon they have finished accessing this {@code ZipFile}.
 643      * This will prevent holding up system resources for an undetermined
 644      * length of time.
 645      *
 646      * @deprecated The {@code finalize} method has been deprecated.
 647      *     Subclasses that override {@code finalize} in order to perform cleanup
 648      *     should be modified to use alternative cleanup mechanisms and
 649      *     to remove the overriding {@code finalize} method.
 650      *     When overriding the {@code finalize} method, its implementation must explicitly
 651      *     ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}.
 652      *     See the specification for {@link Object#finalize()} for further
 653      *     information about migration options.
 654      * @throws IOException if an I/O error has occurred
 655      * @see    java.util.zip.ZipFile#close()
 656      */
 657     @Deprecated(since="9")
 658     protected void finalize() throws IOException {
 659         close();








 660     }
 661 
 662     private void ensureOpen() {
 663         if (closeRequested) {
 664             throw new IllegalStateException("zip file closed");
 665         }
 666         if (zsrc == null) {
 667             throw new IllegalStateException("The object is not initialized.");
 668         }
 669     }
 670 
 671     private void ensureOpenOrZipException() throws IOException {
 672         if (closeRequested) {
 673             throw new ZipException("ZipFile closed");
 674         }
 675     }
 676 
 677     /*
 678      * Inner class implementing the input stream used to read a
 679      * (possibly compressed) zip file entry.
 680      */
 681    private class ZipFileInputStream extends InputStream {
 682         private volatile boolean closeRequested;
 683         private   long pos;     // current position within entry data
 684         protected long rem;     // number of remaining bytes within entry
 685         protected long size;    // uncompressed size of this entry
 686 
 687         ZipFileInputStream(byte[] cen, int cenpos) throws IOException {
 688             rem = CENSIZ(cen, cenpos);
 689             size = CENLEN(cen, cenpos);
 690             pos = CENOFF(cen, cenpos);
 691             // zip64
 692             if (rem == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL ||
 693                 pos == ZIP64_MAGICVAL) {
 694                 checkZIP64(cen, cenpos);
 695             }
 696             // negative for lazy initialization, see getDataOffset();
 697             pos = - (pos + ZipFile.this.zsrc.locpos);
 698         }
 699 
 700         private void checkZIP64(byte[] cen, int cenpos) throws IOException {
 701             int off = cenpos + CENHDR + CENNAM(cen, cenpos);
 702             int end = off + CENEXT(cen, cenpos);
 703             while (off + 4 < end) {
 704                 int tag = get16(cen, off);
 705                 int sz = get16(cen, off + 2);
 706                 off += 4;
 707                 if (off + sz > end)         // invalid data
 708                     break;
 709                 if (tag == EXTID_ZIP64) {
 710                     if (size == ZIP64_MAGICVAL) {
 711                         if (sz < 8 || (off + 8) > end)
 712                             break;
 713                         size = get64(cen, off);
 714                         sz -= 8;
 715                         off += 8;
 716                     }
 717                     if (rem == ZIP64_MAGICVAL) {


 726                             break;
 727                         pos = get64(cen, off);
 728                         sz -= 8;
 729                         off += 8;
 730                     }
 731                     break;
 732                 }
 733                 off += sz;
 734             }
 735         }
 736 
 737        /* The Zip file spec explicitly allows the LOC extra data size to
 738         * be different from the CEN extra data size. Since we cannot trust
 739         * the CEN extra data size, we need to read the LOC to determine
 740         * the entry data offset.
 741         */
 742         private long initDataOffset() throws IOException {
 743             if (pos <= 0) {
 744                 byte[] loc = new byte[LOCHDR];
 745                 pos = -pos;
 746                 int len = ZipFile.this.zsrc.readFullyAt(loc, 0, loc.length, pos);
 747                 if (len != LOCHDR) {
 748                     throw new ZipException("ZipFile error reading zip file");
 749                 }
 750                 if (LOCSIG(loc) != LOCSIG) {
 751                     throw new ZipException("ZipFile invalid LOC header (bad signature)");
 752                 }
 753                 pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc);
 754             }
 755             return pos;
 756         }
 757 
 758         public int read(byte b[], int off, int len) throws IOException {
 759             synchronized (ZipFile.this) {
 760                 ensureOpenOrZipException();
 761                 initDataOffset();
 762                 if (rem == 0) {
 763                     return -1;
 764                 }
 765                 if (len > rem) {
 766                     len = (int) rem;
 767                 }
 768                 if (len <= 0) {
 769                     return 0;
 770                 }
 771                 len = ZipFile.this.zsrc.readAt(b, off, len, pos);
 772                 if (len > 0) {
 773                     pos += len;
 774                     rem -= len;
 775                 }
 776             }
 777             if (rem == 0) {
 778                 close();
 779             }
 780             return len;
 781         }
 782 
 783         public int read() throws IOException {
 784             byte[] b = new byte[1];
 785             if (read(b, 0, 1) == 1) {
 786                 return b[0] & 0xff;
 787             } else {
 788                 return -1;
 789             }
 790         }
 791 


 802             if (rem == 0) {
 803                 close();
 804             }
 805             return n;
 806         }
 807 
 808         public int available() {
 809             return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
 810         }
 811 
 812         public long size() {
 813             return size;
 814         }
 815 
 816         public void close() {
 817             if (closeRequested) {
 818                 return;
 819             }
 820             closeRequested = true;
 821             rem = 0;
 822             synchronized (streams) {
 823                 streams.remove(this);
 824             }
 825         }
 826 
 827         @SuppressWarnings("deprecation")
 828         protected void finalize() {
 829             close();
 830         }
 831     }
 832 
 833     /**
 834      * Returns the names of all non-directory entries that begin with
 835      * "META-INF/" (case ignored). This method is used in JarFile, via
 836      * SharedSecrets, as an optimization when looking up manifest and
 837      * signature file entries. Returns null if no entries were found.
 838      */
 839     private String[] getMetaInfEntryNames() {
 840         synchronized (this) {
 841             ensureOpen();

 842             if (zsrc.metanames == null) {
 843                 return null;
 844             }
 845             String[] names = new String[zsrc.metanames.length];
 846             byte[] cen = zsrc.cen;
 847             for (int i = 0; i < names.length; i++) {
 848                 int pos = zsrc.metanames[i];
 849                 names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos),
 850                                       StandardCharsets.UTF_8);
 851             }
 852             return names;
 853         }
 854     }
 855 
 856     private static boolean isWindows;
 857     static {
 858         SharedSecrets.setJavaUtilZipFileAccess(
 859             new JavaUtilZipFileAccess() {
 860                 public boolean startsWithLocHeader(ZipFile zip) {
 861                     return zip.zsrc.startsWithLoc;
 862                 }
 863                 public String[] getMetaInfEntryNames(ZipFile zip) {
 864                     return zip.getMetaInfEntryNames();
 865                 }
 866              }
 867         );
 868         isWindows = VM.getSavedProperty("os.name").contains("Windows");
 869     }
 870 
 871     private static class Source {
 872         private final Key key;               // the key in files
 873         private int refs = 1;
 874 
 875         private RandomAccessFile zfile;      // zfile of the underlying zip file
 876         private byte[] cen;                  // CEN & ENDHDR
 877         private long locpos;                 // position of first LOC header (usually 0)
 878         private byte[] comment;              // zip file comment
 879                                              // list of meta entries in META-INF dir
 880         private int[] metanames;
 881         private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)


 929 
 930             public boolean equals(Object obj) {
 931                 if (obj instanceof Key) {
 932                     Key key = (Key)obj;
 933                     if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) {
 934                         return false;
 935                     }
 936                     Object fk = attrs.fileKey();
 937                     if (fk != null) {
 938                         return  fk.equals(key.attrs.fileKey());
 939                     } else {
 940                         return file.equals(key.file);
 941                     }
 942                 }
 943                 return false;
 944             }
 945         }
 946         private static final HashMap<Key, Source> files = new HashMap<>();
 947 
 948 
 949         public static Source get(File file, boolean toDelete) throws IOException {
 950             Key key = new Key(file,
 951                               Files.readAttributes(file.toPath(), BasicFileAttributes.class));
 952             Source src = null;
 953             synchronized (files) {
 954                 src = files.get(key);
 955                 if (src != null) {
 956                     src.refs++;
 957                     return src;
 958                 }
 959             }
 960             src = new Source(key, toDelete);
 961 
 962             synchronized (files) {
 963                 if (files.containsKey(key)) {    // someone else put in first
 964                     src.close();                 // close the newly created one
 965                     src = files.get(key);
 966                     src.refs++;
 967                     return src;
 968                 }
 969                 files.put(key, src);
 970                 return src;
 971             }
 972         }
 973 
 974         private static void close(Source src) throws IOException {
 975             synchronized (files) {
 976                 if (--src.refs == 0) {
 977                     files.remove(src.key);
 978                     src.close();
 979                 }
 980             }
 981         }
 982 
 983         private Source(Key key, boolean toDelete) throws IOException {
 984             this.key = key;
 985             if (toDelete) {
 986                 if (isWindows) {
 987                     this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess()
 988                                               .openAndDelete(key.file, "r");
 989                 } else {
 990                     this.zfile = new RandomAccessFile(key.file, "r");
 991                     key.file.delete();
 992                 }
 993             } else {
 994                 this.zfile = new RandomAccessFile(key.file, "r");
 995             }
 996             try {




   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      *


 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


 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);


 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) {


 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 


 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)


 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 {


< prev index next >