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