1 /* 2 * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util.zip; 27 28 import java.io.Closeable; 29 import java.io.InputStream; 30 import java.io.IOException; 31 import java.io.EOFException; 32 import java.io.File; 33 import java.io.RandomAccessFile; 34 import java.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 58 import static java.util.zip.ZipConstants.*; 59 import static java.util.zip.ZipConstants64.*; 60 import static java.util.zip.ZipUtils.*; 61 62 /** 63 * This class is used to read entries from a zip file. 64 * 65 * <p> Unless otherwise noted, passing a {@code null} argument to a constructor 66 * or method in this class will cause a {@link NullPointerException} to be 67 * thrown. 68 * 69 * @author David Connelly 70 */ 71 public 72 class ZipFile implements ZipConstants, Closeable { 73 74 private final String name; // zip file name 75 private volatile boolean closeRequested = false; 76 private Source zsrc; 77 private ZipCoder zc; 78 79 private static final int STORED = ZipEntry.STORED; 80 private static final int DEFLATED = ZipEntry.DEFLATED; 81 82 /** 83 * Mode flag to open a zip file for reading. 84 */ 85 public static final int OPEN_READ = 0x1; 86 87 /** 88 * Mode flag to open a zip file and mark it for deletion. The file will be 89 * deleted some time between the moment that it is opened and the moment 90 * that it is closed, but its contents will remain accessible via the 91 * {@code ZipFile} object until either the close method is invoked or the 92 * virtual machine exits. 93 */ 94 public static final int OPEN_DELETE = 0x4; 95 96 /** 97 * Opens a zip file for reading. 98 * 99 * <p>First, if there is a security manager, its {@code checkRead} 100 * method is called with the {@code name} argument as its argument 101 * to ensure the read is allowed. 102 * 103 * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to 104 * decode the entry names and comments. 105 * 106 * @param name the name of the zip file 107 * @throws ZipException if a ZIP format error has occurred 108 * @throws IOException if an I/O error has occurred 109 * @throws SecurityException if a security manager exists and its 110 * {@code checkRead} method doesn't allow read access to the file. 111 * 112 * @see SecurityManager#checkRead(java.lang.String) 113 */ 114 public ZipFile(String name) throws IOException { 115 this(new File(name), OPEN_READ); 116 } 117 118 /** 119 * Opens a new {@code ZipFile} to read from the specified 120 * {@code File} object in the specified mode. The mode argument 121 * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}. 122 * 123 * <p>First, if there is a security manager, its {@code checkRead} 124 * method is called with the {@code name} argument as its argument to 125 * ensure the read is allowed. 126 * 127 * <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to 128 * decode the entry names and comments 129 * 130 * @param file the ZIP file to be opened for reading 131 * @param mode the mode in which the file is to be opened 132 * @throws ZipException if a ZIP format error has occurred 133 * @throws IOException if an I/O error has occurred 134 * @throws SecurityException if a security manager exists and 135 * its {@code checkRead} method 136 * doesn't allow read access to the file, 137 * or its {@code checkDelete} method doesn't allow deleting 138 * the file when the {@code OPEN_DELETE} flag is set. 139 * @throws IllegalArgumentException if the {@code mode} argument is invalid 140 * @see SecurityManager#checkRead(java.lang.String) 141 * @since 1.3 142 */ 143 public ZipFile(File file, int mode) throws IOException { 144 this(file, mode, StandardCharsets.UTF_8); 145 } 146 147 /** 148 * Opens a ZIP file for reading given the specified File object. 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 * @throws ZipException if a ZIP format error has occurred 155 * @throws IOException if an I/O error has occurred 156 */ 157 public ZipFile(File file) throws ZipException, IOException { 158 this(file, OPEN_READ); 159 } 160 161 /** 162 * Opens a new {@code ZipFile} to read from the specified 163 * {@code File} object in the specified mode. The mode argument 164 * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}. 165 * 166 * <p>First, if there is a security manager, its {@code checkRead} 167 * method is called with the {@code name} argument as its argument to 168 * ensure the read is allowed. 169 * 170 * @param file the ZIP file to be opened for reading 171 * @param mode the mode in which the file is to be opened 172 * @param charset 173 * the {@linkplain java.nio.charset.Charset charset} to 174 * be used to decode the ZIP entry name and comment that are not 175 * encoded by using UTF-8 encoding (indicated by entry's general 176 * purpose flag). 177 * 178 * @throws ZipException if a ZIP format error has occurred 179 * @throws IOException if an I/O error has occurred 180 * 181 * @throws SecurityException 182 * if a security manager exists and its {@code checkRead} 183 * method doesn't allow read access to the file,or its 184 * {@code checkDelete} method doesn't allow deleting the 185 * file when the {@code OPEN_DELETE} flag is set 186 * 187 * @throws IllegalArgumentException if the {@code mode} argument is invalid 188 * 189 * @see SecurityManager#checkRead(java.lang.String) 190 * 191 * @since 1.7 192 */ 193 public ZipFile(File file, int mode, Charset charset) throws IOException 194 { 195 if (((mode & OPEN_READ) == 0) || 196 ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) { 197 throw new IllegalArgumentException("Illegal mode: 0x"+ 198 Integer.toHexString(mode)); 199 } 200 String name = file.getPath(); 201 SecurityManager sm = System.getSecurityManager(); 202 if (sm != null) { 203 sm.checkRead(name); 204 if ((mode & OPEN_DELETE) != 0) { 205 sm.checkDelete(name); 206 } 207 } 208 Objects.requireNonNull(charset, "charset"); 209 this.zc = ZipCoder.get(charset); 210 this.name = name; 211 long t0 = System.nanoTime(); 212 this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0); 213 sun.misc.PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0); 214 sun.misc.PerfCounter.getZipFileCount().increment(); 215 } 216 217 /** 218 * Opens a zip file for reading. 219 * 220 * <p>First, if there is a security manager, its {@code checkRead} 221 * method is called with the {@code name} argument as its argument 222 * to ensure the read is allowed. 223 * 224 * @param name the name of the zip file 225 * @param charset 226 * the {@linkplain java.nio.charset.Charset charset} to 227 * be used to decode the ZIP entry name and comment that are not 228 * encoded by using UTF-8 encoding (indicated by entry's general 229 * purpose flag). 230 * 231 * @throws ZipException if a ZIP format error has occurred 232 * @throws IOException if an I/O error has occurred 233 * @throws SecurityException 234 * if a security manager exists and its {@code checkRead} 235 * method doesn't allow read access to the file 236 * 237 * @see SecurityManager#checkRead(java.lang.String) 238 * 239 * @since 1.7 240 */ 241 public ZipFile(String name, Charset charset) throws IOException 242 { 243 this(new File(name), OPEN_READ, charset); 244 } 245 246 /** 247 * Opens a ZIP file for reading given the specified File object. 248 * 249 * @param file the ZIP file to be opened for reading 250 * @param charset 251 * The {@linkplain java.nio.charset.Charset charset} to be 252 * used to decode the ZIP entry name and comment (ignored if 253 * the <a href="package-summary.html#lang_encoding"> language 254 * encoding bit</a> of the ZIP entry's general purpose bit 255 * flag is set). 256 * 257 * @throws ZipException if a ZIP format error has occurred 258 * @throws IOException if an I/O error has occurred 259 * 260 * @since 1.7 261 */ 262 public ZipFile(File file, Charset charset) throws IOException 263 { 264 this(file, OPEN_READ, charset); 265 } 266 267 /** 268 * Returns the zip file comment, or null if none. 269 * 270 * @return the comment string for the zip file, or null if none 271 * 272 * @throws IllegalStateException if the zip file has been closed 273 * 274 * Since 1.7 275 */ 276 public String getComment() { 277 synchronized (this) { 278 ensureOpen(); 279 if (zsrc.comment == null) { 280 return null; 281 } 282 return zc.toString(zsrc.comment); 283 } 284 } 285 286 /** 287 * Returns the zip file entry for the specified name, or null 288 * if not found. 289 * 290 * @param name the name of the entry 291 * @return the zip file entry, or null if not found 292 * @throws IllegalStateException if the zip file has been closed 293 */ 294 public ZipEntry getEntry(String name) { 295 296 Objects.requireNonNull(name, "name"); 297 synchronized (this) { 298 ensureOpen(); 299 int pos = zsrc.getEntryPos(zc.getBytes(name), true); 300 if (pos != -1) { 301 return getZipEntry(name, pos); 302 } 303 } 304 return null; 305 } 306 307 // The outstanding inputstreams that need to be closed, 308 // mapped to the inflater objects they use. 309 private final Map<InputStream, Inflater> streams = new WeakHashMap<>(); 310 311 /** 312 * Returns an input stream for reading the contents of the specified 313 * zip file entry. 314 * <p> 315 * Closing this ZIP file will, in turn, close all input streams that 316 * have been returned by invocations of this method. 317 * 318 * @param entry the zip file entry 319 * @return the input stream for reading the contents of the specified 320 * zip file entry. 321 * @throws ZipException if a ZIP format error has occurred 322 * @throws IOException if an I/O error has occurred 323 * @throws IllegalStateException if the zip file has been closed 324 */ 325 public InputStream getInputStream(ZipEntry entry) throws IOException { 326 return getInputStream(entry, null); 327 } 328 329 /** 330 * Returns an input stream for reading the contents of the specified 331 * zip file entry. 332 * <p> 333 * Closing this ZIP file will, in turn, close all input streams that 334 * have been returned by invocations of this method. 335 * 336 * @param entry the zip file entry 337 * @param zipCryption instance of ZipCryption 338 * @return the input stream for reading the contents of the specified 339 * zip file entry. 340 * @throws ZipException if a ZIP format error has occurred 341 * @throws IOException if an I/O error has occurred 342 * @throws IllegalStateException if the zip file has been closed 343 */ 344 public InputStream getInputStream(ZipEntry entry, ZipCryption zipCryption) 345 throws IOException { 346 Objects.requireNonNull(entry, "entry"); 347 348 if ((entry.flag & 1) == 1) { 349 Objects.requireNonNull(entry, "Passphrase is required"); 350 zipCryption.reset(); 351 } 352 353 int pos = -1; 354 ZipFileInputStream in = null; 355 synchronized (this) { 356 ensureOpen(); 357 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, zipCryption); 366 switch (CENHOW(zsrc.cen, pos)) { 367 case STORED: 368 if((entry.flag & 1) == 1) { 369 byte[] encryptionHeader = 370 new byte[zipCryption.getEncryptionHeaderSize()]; 371 in.readRaw(encryptionHeader, 0, encryptionHeader.length); 372 zipCryption.decryptBytes(encryptionHeader); 373 374 if (!zipCryption.isValid(entry, encryptionHeader)) { 375 throw new ZipException("possibly incorrect passphrase"); 376 } 377 } 378 synchronized (streams) { 379 streams.put(in, null); 380 } 381 return in; 382 case DEFLATED: 383 // Inflater likes a bit of slack 384 // MORE: Compute good size for inflater stream: 385 long size = CENLEN(zsrc.cen, pos) + 2; 386 if (size > 65536) { 387 size = 8192; 388 } 389 if (size <= 0) { 390 size = 4096; 391 } 392 Inflater inf = getInflater(); 393 394 if((entry.flag & 1) == 1) { 395 byte[] encryptionHeader = 396 new byte[zipCryption.getEncryptionHeaderSize()]; 397 in.readRaw(encryptionHeader, 0, encryptionHeader.length); 398 zipCryption.decryptBytes(encryptionHeader); 399 400 if (!zipCryption.isValid(entry, encryptionHeader)) { 401 throw new ZipException("possibly incorrect passphrase"); 402 } 403 } 404 405 InputStream is = new ZipFileInflaterInputStream(in, inf, (int)size); 406 synchronized (streams) { 407 streams.put(is, inf); 408 } 409 return is; 410 default: 411 throw new ZipException("invalid compression method"); 412 } 413 } 414 } 415 416 private class ZipFileInflaterInputStream extends InflaterInputStream { 417 private volatile boolean closeRequested = false; 418 private boolean eof = false; 419 private final ZipFileInputStream zfin; 420 421 ZipFileInflaterInputStream(ZipFileInputStream zfin, Inflater inf, 422 int size) { 423 super(zfin, inf, size); 424 this.zfin = zfin; 425 } 426 427 public void close() throws IOException { 428 if (closeRequested) 429 return; 430 closeRequested = true; 431 432 super.close(); 433 Inflater inf; 434 synchronized (streams) { 435 inf = streams.remove(this); 436 } 437 if (inf != null) { 438 releaseInflater(inf); 439 } 440 } 441 442 // Override fill() method to provide an extra "dummy" byte 443 // at the end of the input stream. This is required when 444 // using the "nowrap" Inflater option. 445 protected void fill() throws IOException { 446 if (eof) { 447 throw new EOFException("Unexpected end of ZLIB input stream"); 448 } 449 len = in.read(buf, 0, buf.length); 450 if (len == -1) { 451 buf[0] = 0; 452 len = 1; 453 eof = true; 454 } 455 inf.setInput(buf, 0, len); 456 } 457 458 public int available() throws IOException { 459 if (closeRequested) 460 return 0; 461 long avail = zfin.size() - inf.getBytesWritten(); 462 return (avail > (long) Integer.MAX_VALUE ? 463 Integer.MAX_VALUE : (int) avail); 464 } 465 466 protected void finalize() throws Throwable { 467 close(); 468 } 469 } 470 471 /* 472 * Gets an inflater from the list of available inflaters or allocates 473 * a new one. 474 */ 475 private Inflater getInflater() { 476 Inflater inf; 477 synchronized (inflaterCache) { 478 while ((inf = inflaterCache.poll()) != null) { 479 if (!inf.ended()) { 480 return inf; 481 } 482 } 483 } 484 return new Inflater(true); 485 } 486 487 /* 488 * Releases the specified inflater to the list of available inflaters. 489 */ 490 private void releaseInflater(Inflater inf) { 491 if (!inf.ended()) { 492 inf.reset(); 493 synchronized (inflaterCache) { 494 inflaterCache.add(inf); 495 } 496 } 497 } 498 499 // List of available Inflater objects for decompression 500 private final Deque<Inflater> inflaterCache = new ArrayDeque<>(); 501 502 /** 503 * Returns the path name of the ZIP file. 504 * @return the path name of the ZIP file 505 */ 506 public String getName() { 507 return name; 508 } 509 510 private class ZipEntryIterator implements Enumeration<ZipEntry>, Iterator<ZipEntry> { 511 private int i = 0; 512 513 public ZipEntryIterator() { 514 ensureOpen(); 515 } 516 517 public boolean hasMoreElements() { 518 return hasNext(); 519 } 520 521 public boolean hasNext() { 522 synchronized (ZipFile.this) { 523 ensureOpen(); 524 return i < zsrc.total; 525 } 526 } 527 528 public ZipEntry nextElement() { 529 return next(); 530 } 531 532 public ZipEntry next() { 533 synchronized (ZipFile.this) { 534 ensureOpen(); 535 if (i >= zsrc.total) { 536 throw new NoSuchElementException(); 537 } 538 // each "entry" has 3 ints in table entries 539 return getZipEntry(null, zsrc.getEntryPos(i++ * 3)); 540 } 541 } 542 543 public Iterator<ZipEntry> asIterator() { 544 return this; 545 } 546 } 547 548 /** 549 * Returns an enumeration of the ZIP file entries. 550 * @return an enumeration of the ZIP file entries 551 * @throws IllegalStateException if the zip file has been closed 552 */ 553 public Enumeration<? extends ZipEntry> entries() { 554 return new ZipEntryIterator(); 555 } 556 557 /** 558 * Returns an ordered {@code Stream} over the ZIP file entries. 559 * Entries appear in the {@code Stream} in the order they appear in 560 * the central directory of the ZIP file. 561 * 562 * @return an ordered {@code Stream} of entries in this ZIP file 563 * @throws IllegalStateException if the zip file has been closed 564 * @since 1.8 565 */ 566 public Stream<? extends ZipEntry> stream() { 567 return StreamSupport.stream(Spliterators.spliterator( 568 new ZipEntryIterator(), size(), 569 Spliterator.ORDERED | Spliterator.DISTINCT | 570 Spliterator.IMMUTABLE | Spliterator.NONNULL), false); 571 } 572 573 /* Checks ensureOpen() before invoke this method */ 574 private ZipEntry getZipEntry(String name, int pos) { 575 byte[] cen = zsrc.cen; 576 ZipEntry e = new ZipEntry(); 577 int nlen = CENNAM(cen, pos); 578 int elen = CENEXT(cen, pos); 579 int clen = CENCOM(cen, pos); 580 e.flag = CENFLG(cen, pos); // get the flag first 581 if (name != null) { 582 e.name = name; 583 } else { 584 if (!zc.isUTF8() && (e.flag & EFS) != 0) { 585 e.name = zc.toStringUTF8(cen, pos + CENHDR, nlen); 586 } else { 587 e.name = zc.toString(cen, pos + CENHDR, nlen); 588 } 589 } 590 e.xdostime = CENTIM(cen, pos); 591 e.crc = CENCRC(cen, pos); 592 e.size = CENLEN(cen, pos); 593 e.csize = CENSIZ(cen, pos); 594 e.method = CENHOW(cen, pos); 595 if (elen != 0) { 596 e.setExtra0(Arrays.copyOfRange(cen, pos + CENHDR + nlen, 597 pos + CENHDR + nlen + elen), true); 598 } 599 if (clen != 0) { 600 if (!zc.isUTF8() && (e.flag & EFS) != 0) { 601 e.comment = zc.toStringUTF8(cen, pos + CENHDR + nlen + elen, clen); 602 } else { 603 e.comment = zc.toString(cen, pos + CENHDR + nlen + elen, clen); 604 } 605 } 606 return e; 607 } 608 609 /** 610 * Returns the number of entries in the ZIP file. 611 * 612 * @return the number of entries in the ZIP file 613 * @throws IllegalStateException if the zip file has been closed 614 */ 615 public int size() { 616 synchronized (this) { 617 ensureOpen(); 618 return zsrc.total; 619 } 620 } 621 622 /** 623 * Closes the ZIP file. 624 * <p> Closing this ZIP file will close all of the input streams 625 * previously returned by invocations of the {@link #getInputStream 626 * getInputStream} method. 627 * 628 * @throws IOException if an I/O error has occurred 629 */ 630 public void close() throws IOException { 631 if (closeRequested) { 632 return; 633 } 634 closeRequested = true; 635 636 synchronized (this) { 637 // Close streams, release their inflaters 638 synchronized (streams) { 639 if (!streams.isEmpty()) { 640 Map<InputStream, Inflater> copy = new HashMap<>(streams); 641 streams.clear(); 642 for (Map.Entry<InputStream, Inflater> e : copy.entrySet()) { 643 e.getKey().close(); 644 Inflater inf = e.getValue(); 645 if (inf != null) { 646 inf.end(); 647 } 648 } 649 } 650 } 651 // Release cached inflaters 652 synchronized (inflaterCache) { 653 Inflater inf; 654 while ((inf = inflaterCache.poll()) != null) { 655 inf.end(); 656 } 657 } 658 // Release zip src 659 if (zsrc != null) { 660 Source.close(zsrc); 661 zsrc = null; 662 } 663 } 664 } 665 666 /** 667 * Ensures that the system resources held by this ZipFile object are 668 * released when there are no more references to it. 669 * 670 * <p> 671 * Since the time when GC would invoke this method is undetermined, 672 * it is strongly recommended that applications invoke the {@code close} 673 * method as soon they have finished accessing this {@code ZipFile}. 674 * This will prevent holding up system resources for an undetermined 675 * length of time. 676 * 677 * @throws IOException if an I/O error has occurred 678 * @see java.util.zip.ZipFile#close() 679 */ 680 protected void finalize() throws IOException { 681 close(); 682 } 683 684 private void ensureOpen() { 685 if (closeRequested) { 686 throw new IllegalStateException("zip file closed"); 687 } 688 if (zsrc == null) { 689 throw new IllegalStateException("The object is not initialized."); 690 } 691 } 692 693 private void ensureOpenOrZipException() throws IOException { 694 if (closeRequested) { 695 throw new ZipException("ZipFile closed"); 696 } 697 } 698 699 /* 700 * Inner class implementing the input stream used to read a 701 * (possibly compressed) zip file entry. 702 */ 703 private class ZipFileInputStream extends InputStream { 704 private volatile boolean closeRequested = false; 705 private long pos; // current position within entry data 706 protected long rem; // number of remaining bytes within entry 707 protected long size; // uncompressed size of this entry 708 private ZipCryption zipCryption; // ZIP encrypt/decrypt engine 709 710 ZipFileInputStream(byte[] cen, int cenpos, ZipCryption zipCryption) 711 throws IOException { 712 rem = CENSIZ(cen, cenpos); 713 size = CENLEN(cen, cenpos); 714 pos = CENOFF(cen, cenpos); 715 // zip64 716 if (rem == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL || 717 pos == ZIP64_MAGICVAL) { 718 checkZIP64(cen, cenpos); 719 } 720 // negative for lazy initialization, see getDataOffset(); 721 pos = - (pos + ZipFile.this.zsrc.locpos); 722 this.zipCryption = zipCryption; 723 } 724 725 private void checkZIP64(byte[] cen, int cenpos) throws IOException { 726 int off = cenpos + CENHDR + CENNAM(cen, cenpos); 727 int end = off + CENEXT(cen, cenpos); 728 while (off + 4 < end) { 729 int tag = get16(cen, off); 730 int sz = get16(cen, off + 2); 731 off += 4; 732 if (off + sz > end) // invalid data 733 break; 734 if (tag == EXTID_ZIP64) { 735 if (size == ZIP64_MAGICVAL) { 736 if (sz < 8 || (off + 8) > end) 737 break; 738 size = get64(cen, off); 739 sz -= 8; 740 off += 8; 741 } 742 if (rem == ZIP64_MAGICVAL) { 743 if (sz < 8 || (off + 8) > end) 744 break; 745 rem = get64(cen, off); 746 sz -= 8; 747 off += 8; 748 } 749 if (pos == ZIP64_MAGICVAL) { 750 if (sz < 8 || (off + 8) > end) 751 break; 752 pos = get64(cen, off); 753 sz -= 8; 754 off += 8; 755 } 756 break; 757 } 758 off += sz; 759 } 760 } 761 762 /* The Zip file spec explicitly allows the LOC extra data size to 763 * be different from the CEN extra data size. Since we cannot trust 764 * the CEN extra data size, we need to read the LOC to determine 765 * the entry data offset. 766 */ 767 private long initDataOffset() throws IOException { 768 if (pos <= 0) { 769 byte[] loc = new byte[LOCHDR]; 770 pos = -pos; 771 int len = ZipFile.this.zsrc.readFullyAt(loc, 0, loc.length, pos); 772 if (len != LOCHDR) { 773 throw new ZipException("ZipFile error reading zip file"); 774 } 775 if (LOCSIG(loc) != LOCSIG) { 776 throw new ZipException("ZipFile invalid LOC header (bad signature)"); 777 } 778 pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc); 779 } 780 return pos; 781 } 782 783 public int read(byte b[], int off, int len) throws IOException { 784 len = readRaw(b, off, len); 785 786 if (zipCryption != null) { 787 zipCryption.decryptBytes(b, off, len); 788 } 789 790 return len; 791 } 792 793 public int readRaw(byte b[], int off, int len) throws IOException { 794 synchronized (ZipFile.this) { 795 ensureOpenOrZipException(); 796 initDataOffset(); 797 if (rem == 0) { 798 return -1; 799 } 800 if (len > rem) { 801 len = (int) rem; 802 } 803 if (len <= 0) { 804 return 0; 805 } 806 len = ZipFile.this.zsrc.readAt(b, off, len, pos); 807 if (len > 0) { 808 pos += len; 809 rem -= len; 810 } 811 } 812 if (rem == 0) { 813 close(); 814 } 815 return len; 816 } 817 818 public int read() throws IOException { 819 byte[] b = new byte[1]; 820 if (read(b, 0, 1) == 1) { 821 return b[0] & 0xff; 822 } else { 823 return -1; 824 } 825 } 826 827 public long skip(long n) throws IOException { 828 synchronized (ZipFile.this) { 829 ensureOpenOrZipException(); 830 initDataOffset(); 831 if (n > rem) { 832 n = rem; 833 } 834 pos += n; 835 rem -= n; 836 } 837 if (rem == 0) { 838 close(); 839 } 840 return n; 841 } 842 843 public int available() { 844 return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem; 845 } 846 847 public long size() { 848 return size; 849 } 850 851 public void close() { 852 if (closeRequested) { 853 return; 854 } 855 closeRequested = true; 856 rem = 0; 857 synchronized (streams) { 858 streams.remove(this); 859 } 860 } 861 862 protected void finalize() { 863 close(); 864 } 865 } 866 867 static { 868 SharedSecrets.setJavaUtilZipFileAccess( 869 new JavaUtilZipFileAccess() { 870 public boolean startsWithLocHeader(ZipFile zip) { 871 return zip.zsrc.startsWithLoc; 872 } 873 public String[] getMetaInfEntryNames(ZipFile zip) { 874 return zip.getMetaInfEntryNames(); 875 } 876 } 877 ); 878 } 879 880 /* 881 * Returns an array of strings representing the names of all entries 882 * that begin with "META-INF/" (case ignored). This method is used 883 * in JarFile, via SharedSecrets, as an optimization when looking up 884 * manifest and signature file entries. Returns null if no entries 885 * were found. 886 */ 887 private String[] getMetaInfEntryNames() { 888 synchronized (this) { 889 ensureOpen(); 890 if (zsrc.metanames.size() == 0) { 891 return null; 892 } 893 String[] names = new String[zsrc.metanames.size()]; 894 byte[] cen = zsrc.cen; 895 for (int i = 0; i < names.length; i++) { 896 int pos = zsrc.metanames.get(i); 897 names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos), 898 StandardCharsets.UTF_8); 899 } 900 return names; 901 } 902 } 903 904 private static class Source { 905 private final Key key; // the key in files 906 private int refs = 1; 907 908 private RandomAccessFile zfile; // zfile of the underlying zip file 909 private byte[] cen; // CEN & ENDHDR 910 private long locpos; // position of first LOC header (usually 0) 911 private byte[] comment; // zip file comment 912 // list of meta entries in META-INF dir 913 private ArrayList<Integer> metanames = new ArrayList<>(); 914 private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true) 915 916 // A Hashmap for all entries. 917 // 918 // A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR, 919 // We might have a lot of these in a typical system. In order to save space we don't 920 // keep the name in memory, but merely remember a 32 bit {@code hash} value of the 921 // entry name and its offset {@code pos} in the central directory hdeader. 922 // 923 // private static class Entry { 924 // int hash; // 32 bit hashcode on name 925 // int next; // hash chain: index into entries 926 // int pos; // Offset of central directory file header 927 // } 928 // private Entry[] entries; // array of hashed cen entry 929 // 930 // To reduce the total size of entries further, we use a int[] here to store 3 "int" 931 // {@code hash}, {@code next and {@code "pos for each entry. The entry can then be 932 // referred by their index of their positions in the {@code entries}. 933 // 934 private int[] entries; // array of hashed cen entry 935 private int addEntry(int index, int hash, int next, int pos) { 936 entries[index++] = hash; 937 entries[index++] = next; 938 entries[index++] = pos; 939 return index; 940 } 941 private int getEntryHash(int index) { return entries[index]; } 942 private int getEntryNext(int index) { return entries[index + 1]; } 943 private int getEntryPos(int index) { return entries[index + 2]; } 944 private static final int ZIP_ENDCHAIN = -1; 945 private int total; // total number of entries 946 private int[] table; // Hash chain heads: indexes into entries 947 private int tablelen; // number of hash heads 948 949 private static class Key { 950 BasicFileAttributes attrs; 951 File file; 952 953 public Key(File file, BasicFileAttributes attrs) { 954 this.attrs = attrs; 955 this.file = file; 956 } 957 958 public int hashCode() { 959 long t = attrs.lastModifiedTime().toMillis(); 960 return ((int)(t ^ (t >>> 32))) + file.hashCode(); 961 } 962 963 public boolean equals(Object obj) { 964 if (obj instanceof Key) { 965 Key key = (Key)obj; 966 if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) { 967 return false; 968 } 969 Object fk = attrs.fileKey(); 970 if (fk != null) { 971 return fk.equals(key.attrs.fileKey()); 972 } else { 973 return file.equals(key.file); 974 } 975 } 976 return false; 977 } 978 } 979 private static final HashMap<Key, Source> files = new HashMap<>(); 980 981 982 public static Source get(File file, boolean toDelete) throws IOException { 983 Key key = new Key(file, 984 Files.readAttributes(file.toPath(), BasicFileAttributes.class)); 985 Source src = null; 986 synchronized (files) { 987 src = files.get(key); 988 if (src != null) { 989 src.refs++; 990 return src; 991 } 992 } 993 src = new Source(key, toDelete); 994 995 synchronized (files) { 996 if (files.containsKey(key)) { // someone else put in first 997 src.close(); // close the newly created one 998 src = files.get(key); 999 src.refs++; 1000 return src; 1001 } 1002 files.put(key, src); 1003 return src; 1004 } 1005 } 1006 1007 private static void close(Source src) throws IOException { 1008 synchronized (files) { 1009 if (--src.refs == 0) { 1010 files.remove(src.key); 1011 src.close(); 1012 } 1013 } 1014 } 1015 1016 private Source(Key key, boolean toDelete) throws IOException { 1017 this.key = key; 1018 this.zfile = new RandomAccessFile(key.file, "r"); 1019 if (toDelete) { 1020 key.file.delete(); 1021 } 1022 try { 1023 initCEN(-1); 1024 byte[] buf = new byte[4]; 1025 readFullyAt(buf, 0, 4, 0); 1026 this.startsWithLoc = (LOCSIG(buf) == LOCSIG); 1027 } catch (IOException x) { 1028 try { 1029 this.zfile.close(); 1030 } catch (IOException xx) {} 1031 throw x; 1032 } 1033 } 1034 1035 private void close() throws IOException { 1036 zfile.close(); 1037 zfile = null; 1038 cen = null; 1039 entries = null; 1040 table = null; 1041 metanames = null; 1042 } 1043 1044 private static final int BUF_SIZE = 8192; 1045 private final int readFullyAt(byte[] buf, int off, int len, long pos) 1046 throws IOException 1047 { 1048 synchronized(zfile) { 1049 zfile.seek(pos); 1050 int N = len; 1051 while (N > 0) { 1052 int n = Math.min(BUF_SIZE, N); 1053 zfile.readFully(buf, off, n); 1054 off += n; 1055 N -= n; 1056 } 1057 return len; 1058 } 1059 } 1060 1061 private final int readAt(byte[] buf, int off, int len, long pos) 1062 throws IOException 1063 { 1064 synchronized(zfile) { 1065 zfile.seek(pos); 1066 return zfile.read(buf, off, len); 1067 } 1068 } 1069 1070 private static final int hashN(byte[] a, int off, int len) { 1071 int h = 1; 1072 while (len-- > 0) { 1073 h = 31 * h + a[off++]; 1074 } 1075 return h; 1076 } 1077 1078 private static final int hash_append(int hash, byte b) { 1079 return hash * 31 + b; 1080 } 1081 1082 private static class End { 1083 int centot; // 4 bytes 1084 long cenlen; // 4 bytes 1085 long cenoff; // 4 bytes 1086 long endpos; // 4 bytes 1087 } 1088 1089 /* 1090 * Searches for end of central directory (END) header. The contents of 1091 * the END header will be read and placed in endbuf. Returns the file 1092 * position of the END header, otherwise returns -1 if the END header 1093 * was not found or an error occurred. 1094 */ 1095 private End findEND() throws IOException { 1096 long ziplen = zfile.length(); 1097 if (ziplen <= 0) 1098 zerror("zip file is empty"); 1099 End end = new End(); 1100 byte[] buf = new byte[READBLOCKSZ]; 1101 long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0; 1102 long minPos = minHDR - (buf.length - ENDHDR); 1103 for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) { 1104 int off = 0; 1105 if (pos < 0) { 1106 // Pretend there are some NUL bytes before start of file 1107 off = (int)-pos; 1108 Arrays.fill(buf, 0, off, (byte)0); 1109 } 1110 int len = buf.length - off; 1111 if (readFullyAt(buf, off, len, pos + off) != len ) { 1112 zerror("zip END header not found"); 1113 } 1114 // Now scan the block backwards for END header signature 1115 for (int i = buf.length - ENDHDR; i >= 0; i--) { 1116 if (buf[i+0] == (byte)'P' && 1117 buf[i+1] == (byte)'K' && 1118 buf[i+2] == (byte)'\005' && 1119 buf[i+3] == (byte)'\006') { 1120 // Found ENDSIG header 1121 byte[] endbuf = Arrays.copyOfRange(buf, i, i + ENDHDR); 1122 end.centot = ENDTOT(endbuf); 1123 end.cenlen = ENDSIZ(endbuf); 1124 end.cenoff = ENDOFF(endbuf); 1125 end.endpos = pos + i; 1126 int comlen = ENDCOM(endbuf); 1127 if (end.endpos + ENDHDR + comlen != ziplen) { 1128 // ENDSIG matched, however the size of file comment in it does 1129 // not match the real size. One "common" cause for this problem 1130 // is some "extra" bytes are padded at the end of the zipfile. 1131 // Let's do some extra verification, we don't care about the 1132 // performance in this situation. 1133 byte[] sbuf = new byte[4]; 1134 long cenpos = end.endpos - end.cenlen; 1135 long locpos = cenpos - end.cenoff; 1136 if (cenpos < 0 || 1137 locpos < 0 || 1138 readFullyAt(sbuf, 0, sbuf.length, cenpos) != 4 || 1139 GETSIG(sbuf) != CENSIG || 1140 readFullyAt(sbuf, 0, sbuf.length, locpos) != 4 || 1141 GETSIG(sbuf) != LOCSIG) { 1142 continue; 1143 } 1144 } 1145 if (comlen > 0) { // this zip file has comlen 1146 comment = new byte[comlen]; 1147 if (readFullyAt(comment, 0, comlen, end.endpos + ENDHDR) != comlen) { 1148 zerror("zip comment read failed"); 1149 } 1150 } 1151 if (end.cenlen == ZIP64_MAGICVAL || 1152 end.cenoff == ZIP64_MAGICVAL || 1153 end.centot == ZIP64_MAGICCOUNT) 1154 { 1155 // need to find the zip64 end; 1156 try { 1157 byte[] loc64 = new byte[ZIP64_LOCHDR]; 1158 if (readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR) 1159 != loc64.length || GETSIG(loc64) != ZIP64_LOCSIG) { 1160 return end; 1161 } 1162 long end64pos = ZIP64_LOCOFF(loc64); 1163 byte[] end64buf = new byte[ZIP64_ENDHDR]; 1164 if (readFullyAt(end64buf, 0, end64buf.length, end64pos) 1165 != end64buf.length || GETSIG(end64buf) != ZIP64_ENDSIG) { 1166 return end; 1167 } 1168 // end64 found, re-calcualte everything. 1169 end.cenlen = ZIP64_ENDSIZ(end64buf); 1170 end.cenoff = ZIP64_ENDOFF(end64buf); 1171 end.centot = (int)ZIP64_ENDTOT(end64buf); // assume total < 2g 1172 end.endpos = end64pos; 1173 } catch (IOException x) {} // no zip64 loc/end 1174 } 1175 return end; 1176 } 1177 } 1178 } 1179 zerror("zip END header not found"); 1180 return null; //make compiler happy 1181 } 1182 1183 // Reads zip file central directory. 1184 private void initCEN(int knownTotal) throws IOException { 1185 if (knownTotal == -1) { 1186 End end = findEND(); 1187 if (end.endpos == 0) { 1188 locpos = 0; 1189 total = 0; 1190 entries = new int[0]; 1191 cen = null; 1192 return; // only END header present 1193 } 1194 if (end.cenlen > end.endpos) 1195 zerror("invalid END header (bad central directory size)"); 1196 long cenpos = end.endpos - end.cenlen; // position of CEN table 1197 // Get position of first local file (LOC) header, taking into 1198 // account that there may be a stub prefixed to the zip file. 1199 locpos = cenpos - end.cenoff; 1200 if (locpos < 0) { 1201 zerror("invalid END header (bad central directory offset)"); 1202 } 1203 // read in the CEN and END 1204 cen = new byte[(int)(end.cenlen + ENDHDR)]; 1205 if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) { 1206 zerror("read CEN tables failed"); 1207 } 1208 total = end.centot; 1209 } else { 1210 total = knownTotal; 1211 } 1212 // hash table for entries 1213 entries = new int[total * 3]; 1214 tablelen = ((total/2) | 1); // Odd -> fewer collisions 1215 table = new int[tablelen]; 1216 Arrays.fill(table, ZIP_ENDCHAIN); 1217 int idx = 0; 1218 int hash = 0; 1219 int next = -1; 1220 1221 // list for all meta entries 1222 metanames = new ArrayList<>(); 1223 1224 // Iterate through the entries in the central directory 1225 int i = 0; 1226 int hsh = 0; 1227 int pos = 0; 1228 int limit = cen.length - ENDHDR; 1229 while (pos + CENHDR <= limit) { 1230 if (i >= total) { 1231 // This will only happen if the zip file has an incorrect 1232 // ENDTOT field, which usually means it contains more than 1233 // 65535 entries. 1234 initCEN(countCENHeaders(cen, limit)); 1235 return; 1236 } 1237 if (CENSIG(cen, pos) != CENSIG) 1238 zerror("invalid CEN header (bad signature)"); 1239 int method = CENHOW(cen, pos); 1240 int nlen = CENNAM(cen, pos); 1241 int elen = CENEXT(cen, pos); 1242 int clen = CENCOM(cen, pos); 1243 if (method != STORED && method != DEFLATED) 1244 zerror("invalid CEN header (bad compression method: " + method + ")"); 1245 if (pos + CENHDR + nlen > limit) 1246 zerror("invalid CEN header (bad header size)"); 1247 // Record the CEN offset and the name hash in our hash cell. 1248 hash = hashN(cen, pos + CENHDR, nlen); 1249 hsh = (hash & 0x7fffffff) % tablelen; 1250 next = table[hsh]; 1251 table[hsh] = idx; 1252 idx = addEntry(idx, hash, next, pos); 1253 // Adds name to metanames. 1254 if (isMetaName(cen, pos + CENHDR, nlen)) { 1255 metanames.add(pos); 1256 } 1257 // skip ext and comment 1258 pos += (CENHDR + nlen + elen + clen); 1259 i++; 1260 } 1261 total = i; 1262 if (pos + ENDHDR != cen.length) { 1263 zerror("invalid CEN header (bad header size)"); 1264 } 1265 } 1266 1267 private static void zerror(String msg) throws ZipException { 1268 throw new ZipException(msg); 1269 } 1270 1271 /* 1272 * Returns the {@code pos} of the zip cen entry corresponding to the 1273 * specified entry name, or -1 if not found. 1274 */ 1275 private int getEntryPos(byte[] name, boolean addSlash) { 1276 if (total == 0) { 1277 return -1; 1278 } 1279 int hsh = hashN(name, 0, name.length); 1280 int idx = table[(hsh & 0x7fffffff) % tablelen]; 1281 /* 1282 * This while loop is an optimization where a double lookup 1283 * for name and name+/ is being performed. The name char 1284 * array has enough room at the end to try again with a 1285 * slash appended if the first table lookup does not succeed. 1286 */ 1287 while(true) { 1288 /* 1289 * Search down the target hash chain for a entry whose 1290 * 32 bit hash matches the hashed name. 1291 */ 1292 while (idx != ZIP_ENDCHAIN) { 1293 if (getEntryHash(idx) == hsh) { 1294 // The CEN name must match the specfied one 1295 int pos = getEntryPos(idx); 1296 if (name.length == CENNAM(cen, pos)) { 1297 boolean matched = true; 1298 int nameoff = pos + CENHDR; 1299 for (int i = 0; i < name.length; i++) { 1300 if (name[i] != cen[nameoff++]) { 1301 matched = false; 1302 break; 1303 } 1304 } 1305 if (matched) { 1306 return pos; 1307 } 1308 } 1309 } 1310 idx = getEntryNext(idx); 1311 } 1312 /* If not addSlash, or slash is already there, we are done */ 1313 if (!addSlash || name[name.length - 1] == '/') { 1314 return -1; 1315 } 1316 /* Add slash and try once more */ 1317 name = Arrays.copyOf(name, name.length + 1); 1318 name[name.length - 1] = '/'; 1319 hsh = hash_append(hsh, (byte)'/'); 1320 //idx = table[hsh % tablelen]; 1321 idx = table[(hsh & 0x7fffffff) % tablelen]; 1322 addSlash = false; 1323 } 1324 } 1325 1326 private static byte[] metainf = new byte[] { 1327 'M', 'E', 'T', 'A', '-', 'I' , 'N', 'F', '/', 1328 }; 1329 1330 /* 1331 * Returns true if the specified entry's name begins with the string 1332 * "META-INF/" irrespective of case. 1333 */ 1334 private static boolean isMetaName(byte[] name, int off, int len) { 1335 if (len < 9 || (name[off] != 'M' && name[off] != 'm')) { // sizeof("META-INF/") - 1 1336 return false; 1337 } 1338 off++; 1339 for (int i = 1; i < metainf.length; i++) { 1340 byte c = name[off++]; 1341 // Avoid toupper; it's locale-dependent 1342 if (c >= 'a' && c <= 'z') { 1343 c += 'A' - 'a'; 1344 } 1345 if (metainf[i] != c) { 1346 return false; 1347 } 1348 } 1349 return true; 1350 } 1351 1352 /* 1353 * Counts the number of CEN headers in a central directory extending 1354 * from BEG to END. Might return a bogus answer if the zip file is 1355 * corrupt, but will not crash. 1356 */ 1357 static int countCENHeaders(byte[] cen, int end) { 1358 int count = 0; 1359 int pos = 0; 1360 while (pos + CENHDR <= end) { 1361 count++; 1362 pos += (CENHDR + CENNAM(cen, pos) + CENEXT(cen, pos) + CENCOM(cen, pos)); 1363 } 1364 return count; 1365 } 1366 } 1367 }