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 & EFS) != 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) & EFS) != 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 & EFS) != 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 & EFS) != 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 /* The Zip file spec explicitly allows the LOC extra data size to 988 * be different from the CEN extra data size. Since we cannot trust 989 * the CEN extra data size, we need to read the LOC to determine 990 * the entry data offset. 991 */ 992 private long initDataOffset() throws IOException { 993 if (pos <= 0) { 994 byte[] loc = new byte[LOCHDR]; 995 pos = -pos; 996 int len = ZipFile.this.res.zsrc.readFullyAt(loc, 0, loc.length, pos); 997 if (len != LOCHDR) { 998 throw new ZipException("ZipFile error reading zip file"); 999 } 1000 if (LOCSIG(loc) != LOCSIG) { 1001 throw new ZipException("ZipFile invalid LOC header (bad signature)"); 1002 } 1003 pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc); 1004 } 1005 return pos; 1006 } 1007 1008 public int read(byte b[], int off, int len) throws IOException { 1009 synchronized (ZipFile.this) { 1010 ensureOpenOrZipException(); 1011 initDataOffset(); 1012 if (rem == 0) { 1013 return -1; 1014 } 1015 if (len > rem) { 1016 len = (int) rem; 1017 } 1018 if (len <= 0) { 1019 return 0; 1020 } 1021 len = ZipFile.this.res.zsrc.readAt(b, off, len, pos); 1022 if (len > 0) { 1023 pos += len; 1024 rem -= len; 1025 } 1026 } 1027 if (rem == 0) { 1028 close(); 1029 } 1030 return len; 1031 } 1032 1033 public int read() throws IOException { 1034 byte[] b = new byte[1]; 1035 if (read(b, 0, 1) == 1) { 1036 return b[0] & 0xff; 1037 } else { 1038 return -1; 1039 } 1040 } 1041 1042 public long skip(long n) throws IOException { 1043 synchronized (ZipFile.this) { 1044 initDataOffset(); 1045 if (n > rem) { 1046 n = rem; 1047 } 1048 pos += n; 1049 rem -= n; 1050 } 1051 if (rem == 0) { 1052 close(); 1053 } 1054 return n; 1055 } 1056 1057 public int available() { 1058 return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem; 1059 } 1060 1061 public long size() { 1062 return size; 1063 } 1064 1065 public void close() { 1066 if (closeRequested) { 1067 return; 1068 } 1069 closeRequested = true; 1070 rem = 0; 1071 synchronized (res.istreams) { 1072 res.istreams.remove(this); 1073 } 1074 } 1075 1076 } 1077 1078 /** 1079 * Returns the names of all non-directory entries that begin with 1080 * "META-INF/" (case ignored). This method is used in JarFile, via 1081 * SharedSecrets, as an optimization when looking up manifest and 1082 * signature file entries. Returns null if no entries were found. 1083 */ 1084 private String[] getMetaInfEntryNames() { 1085 synchronized (this) { 1086 ensureOpen(); 1087 Source zsrc = res.zsrc; 1088 if (zsrc.metanames == null) { 1089 return null; 1090 } 1091 String[] names = new String[zsrc.metanames.length]; 1092 byte[] cen = zsrc.cen; 1093 for (int i = 0; i < names.length; i++) { 1094 int pos = zsrc.metanames[i]; 1095 names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos), 1096 StandardCharsets.UTF_8); 1097 } 1098 return names; 1099 } 1100 } 1101 1102 private static boolean isWindows; 1103 private static final JavaLangAccess JLA; 1104 1105 static { 1106 SharedSecrets.setJavaUtilZipFileAccess( 1107 new JavaUtilZipFileAccess() { 1108 @Override 1109 public boolean startsWithLocHeader(ZipFile zip) { 1110 return zip.res.zsrc.startsWithLoc; 1111 } 1112 @Override 1113 public String[] getMetaInfEntryNames(ZipFile zip) { 1114 return zip.getMetaInfEntryNames(); 1115 } 1116 @Override 1117 public JarEntry getEntry(ZipFile zip, String name, 1118 Function<String, JarEntry> func) { 1119 return (JarEntry)zip.getEntry(name, func); 1120 } 1121 @Override 1122 public Enumeration<JarEntry> entries(ZipFile zip, 1123 Function<String, JarEntry> func) { 1124 return zip.entries(func); 1125 } 1126 @Override 1127 public Stream<JarEntry> stream(ZipFile zip, 1128 Function<String, JarEntry> func) { 1129 return zip.stream(func); 1130 } 1131 @Override 1132 public Stream<String> entryNameStream(ZipFile zip) { 1133 return zip.entryNameStream(); 1134 } 1135 } 1136 ); 1137 JLA = jdk.internal.misc.SharedSecrets.getJavaLangAccess(); 1138 isWindows = VM.getSavedProperty("os.name").contains("Windows"); 1139 } 1140 1141 private static class Source { 1142 private final Key key; // the key in files 1143 private int refs = 1; 1144 1145 private RandomAccessFile zfile; // zfile of the underlying zip file 1146 private byte[] cen; // CEN & ENDHDR 1147 private long locpos; // position of first LOC header (usually 0) 1148 private byte[] comment; // zip file comment 1149 // list of meta entries in META-INF dir 1150 private int[] metanames; 1151 private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true) 1152 1153 // A Hashmap for all entries. 1154 // 1155 // A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR, 1156 // We might have a lot of these in a typical system. In order to save space we don't 1157 // keep the name in memory, but merely remember a 32 bit {@code hash} value of the 1158 // entry name and its offset {@code pos} in the central directory hdeader. 1159 // 1160 // private static class Entry { 1161 // int hash; // 32 bit hashcode on name 1162 // int next; // hash chain: index into entries 1163 // int pos; // Offset of central directory file header 1164 // } 1165 // private Entry[] entries; // array of hashed cen entry 1166 // 1167 // To reduce the total size of entries further, we use a int[] here to store 3 "int" 1168 // {@code hash}, {@code next and {@code "pos for each entry. The entry can then be 1169 // referred by their index of their positions in the {@code entries}. 1170 // 1171 private int[] entries; // array of hashed cen entry 1172 private int addEntry(int index, int hash, int next, int pos) { 1173 entries[index++] = hash; 1174 entries[index++] = next; 1175 entries[index++] = pos; 1176 return index; 1177 } 1178 private int getEntryHash(int index) { return entries[index]; } 1179 private int getEntryNext(int index) { return entries[index + 1]; } 1180 private int getEntryPos(int index) { return entries[index + 2]; } 1181 private static final int ZIP_ENDCHAIN = -1; 1182 private int total; // total number of entries 1183 private int[] table; // Hash chain heads: indexes into entries 1184 private int tablelen; // number of hash heads 1185 1186 private static class Key { 1187 BasicFileAttributes attrs; 1188 File file; 1189 1190 public Key(File file, BasicFileAttributes attrs) { 1191 this.attrs = attrs; 1192 this.file = file; 1193 } 1194 1195 public int hashCode() { 1196 long t = attrs.lastModifiedTime().toMillis(); 1197 return ((int)(t ^ (t >>> 32))) + file.hashCode(); 1198 } 1199 1200 public boolean equals(Object obj) { 1201 if (obj instanceof Key) { 1202 Key key = (Key)obj; 1203 if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) { 1204 return false; 1205 } 1206 Object fk = attrs.fileKey(); 1207 if (fk != null) { 1208 return fk.equals(key.attrs.fileKey()); 1209 } else { 1210 return file.equals(key.file); 1211 } 1212 } 1213 return false; 1214 } 1215 } 1216 private static final HashMap<Key, Source> files = new HashMap<>(); 1217 1218 1219 static Source get(File file, boolean toDelete) throws IOException { 1220 Key key = new Key(file, 1221 Files.readAttributes(file.toPath(), BasicFileAttributes.class)); 1222 Source src; 1223 synchronized (files) { 1224 src = files.get(key); 1225 if (src != null) { 1226 src.refs++; 1227 return src; 1228 } 1229 } 1230 src = new Source(key, toDelete); 1231 1232 synchronized (files) { 1233 if (files.containsKey(key)) { // someone else put in first 1234 src.close(); // close the newly created one 1235 src = files.get(key); 1236 src.refs++; 1237 return src; 1238 } 1239 files.put(key, src); 1240 return src; 1241 } 1242 } 1243 1244 static void release(Source src) throws IOException { 1245 synchronized (files) { 1246 if (src != null && --src.refs == 0) { 1247 files.remove(src.key); 1248 src.close(); 1249 } 1250 } 1251 } 1252 1253 private Source(Key key, boolean toDelete) throws IOException { 1254 this.key = key; 1255 if (toDelete) { 1256 if (isWindows) { 1257 this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess() 1258 .openAndDelete(key.file, "r"); 1259 } else { 1260 this.zfile = new RandomAccessFile(key.file, "r"); 1261 key.file.delete(); 1262 } 1263 } else { 1264 this.zfile = new RandomAccessFile(key.file, "r"); 1265 } 1266 try { 1267 initCEN(-1); 1268 byte[] buf = new byte[4]; 1269 readFullyAt(buf, 0, 4, 0); 1270 this.startsWithLoc = (LOCSIG(buf) == LOCSIG); 1271 } catch (IOException x) { 1272 try { 1273 this.zfile.close(); 1274 } catch (IOException xx) {} 1275 throw x; 1276 } 1277 } 1278 1279 private void close() throws IOException { 1280 zfile.close(); 1281 zfile = null; 1282 cen = null; 1283 entries = null; 1284 table = null; 1285 metanames = null; 1286 } 1287 1288 private static final int BUF_SIZE = 8192; 1289 private final int readFullyAt(byte[] buf, int off, int len, long pos) 1290 throws IOException 1291 { 1292 synchronized(zfile) { 1293 zfile.seek(pos); 1294 int N = len; 1295 while (N > 0) { 1296 int n = Math.min(BUF_SIZE, N); 1297 zfile.readFully(buf, off, n); 1298 off += n; 1299 N -= n; 1300 } 1301 return len; 1302 } 1303 } 1304 1305 private final int readAt(byte[] buf, int off, int len, long pos) 1306 throws IOException 1307 { 1308 synchronized(zfile) { 1309 zfile.seek(pos); 1310 return zfile.read(buf, off, len); 1311 } 1312 } 1313 1314 private static final int hashN(byte[] a, int off, int len) { 1315 int h = 1; 1316 while (len-- > 0) { 1317 h = 31 * h + a[off++]; 1318 } 1319 return h; 1320 } 1321 1322 private static final int hash_append(int hash, byte b) { 1323 return hash * 31 + b; 1324 } 1325 1326 private static class End { 1327 int centot; // 4 bytes 1328 long cenlen; // 4 bytes 1329 long cenoff; // 4 bytes 1330 long endpos; // 4 bytes 1331 } 1332 1333 /* 1334 * Searches for end of central directory (END) header. The contents of 1335 * the END header will be read and placed in endbuf. Returns the file 1336 * position of the END header, otherwise returns -1 if the END header 1337 * was not found or an error occurred. 1338 */ 1339 private End findEND() throws IOException { 1340 long ziplen = zfile.length(); 1341 if (ziplen <= 0) 1342 zerror("zip file is empty"); 1343 End end = new End(); 1344 byte[] buf = new byte[READBLOCKSZ]; 1345 long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0; 1346 long minPos = minHDR - (buf.length - ENDHDR); 1347 for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) { 1348 int off = 0; 1349 if (pos < 0) { 1350 // Pretend there are some NUL bytes before start of file 1351 off = (int)-pos; 1352 Arrays.fill(buf, 0, off, (byte)0); 1353 } 1354 int len = buf.length - off; 1355 if (readFullyAt(buf, off, len, pos + off) != len ) { 1356 zerror("zip END header not found"); 1357 } 1358 // Now scan the block backwards for END header signature 1359 for (int i = buf.length - ENDHDR; i >= 0; i--) { 1360 if (buf[i+0] == (byte)'P' && 1361 buf[i+1] == (byte)'K' && 1362 buf[i+2] == (byte)'\005' && 1363 buf[i+3] == (byte)'\006') { 1364 // Found ENDSIG header 1365 byte[] endbuf = Arrays.copyOfRange(buf, i, i + ENDHDR); 1366 end.centot = ENDTOT(endbuf); 1367 end.cenlen = ENDSIZ(endbuf); 1368 end.cenoff = ENDOFF(endbuf); 1369 end.endpos = pos + i; 1370 int comlen = ENDCOM(endbuf); 1371 if (end.endpos + ENDHDR + comlen != ziplen) { 1372 // ENDSIG matched, however the size of file comment in it does 1373 // not match the real size. One "common" cause for this problem 1374 // is some "extra" bytes are padded at the end of the zipfile. 1375 // Let's do some extra verification, we don't care about the 1376 // performance in this situation. 1377 byte[] sbuf = new byte[4]; 1378 long cenpos = end.endpos - end.cenlen; 1379 long locpos = cenpos - end.cenoff; 1380 if (cenpos < 0 || 1381 locpos < 0 || 1382 readFullyAt(sbuf, 0, sbuf.length, cenpos) != 4 || 1383 GETSIG(sbuf) != CENSIG || 1384 readFullyAt(sbuf, 0, sbuf.length, locpos) != 4 || 1385 GETSIG(sbuf) != LOCSIG) { 1386 continue; 1387 } 1388 } 1389 if (comlen > 0) { // this zip file has comlen 1390 comment = new byte[comlen]; 1391 if (readFullyAt(comment, 0, comlen, end.endpos + ENDHDR) != comlen) { 1392 zerror("zip comment read failed"); 1393 } 1394 } 1395 // must check for a zip64 end record; it is always permitted to be present 1396 try { 1397 byte[] loc64 = new byte[ZIP64_LOCHDR]; 1398 if (end.endpos < ZIP64_LOCHDR || 1399 readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR) 1400 != loc64.length || GETSIG(loc64) != ZIP64_LOCSIG) { 1401 return end; 1402 } 1403 long end64pos = ZIP64_LOCOFF(loc64); 1404 byte[] end64buf = new byte[ZIP64_ENDHDR]; 1405 if (readFullyAt(end64buf, 0, end64buf.length, end64pos) 1406 != end64buf.length || GETSIG(end64buf) != ZIP64_ENDSIG) { 1407 return end; 1408 } 1409 // end64 candidate found, 1410 long cenlen64 = ZIP64_ENDSIZ(end64buf); 1411 long cenoff64 = ZIP64_ENDOFF(end64buf); 1412 long centot64 = ZIP64_ENDTOT(end64buf); 1413 // double-check 1414 if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MAGICVAL || 1415 cenoff64 != end.cenoff && end.cenoff != ZIP64_MAGICVAL || 1416 centot64 != end.centot && end.centot != ZIP64_MAGICCOUNT) { 1417 return end; 1418 } 1419 // to use the end64 values 1420 end.cenlen = cenlen64; 1421 end.cenoff = cenoff64; 1422 end.centot = (int)centot64; // assume total < 2g 1423 end.endpos = end64pos; 1424 } catch (IOException x) {} // no zip64 loc/end 1425 return end; 1426 } 1427 } 1428 } 1429 zerror("zip END header not found"); 1430 return null; //make compiler happy 1431 } 1432 1433 // Reads zip file central directory. 1434 private void initCEN(int knownTotal) throws IOException { 1435 if (knownTotal == -1) { 1436 End end = findEND(); 1437 if (end.endpos == 0) { 1438 locpos = 0; 1439 total = 0; 1440 entries = new int[0]; 1441 cen = null; 1442 return; // only END header present 1443 } 1444 if (end.cenlen > end.endpos) 1445 zerror("invalid END header (bad central directory size)"); 1446 long cenpos = end.endpos - end.cenlen; // position of CEN table 1447 // Get position of first local file (LOC) header, taking into 1448 // account that there may be a stub prefixed to the zip file. 1449 locpos = cenpos - end.cenoff; 1450 if (locpos < 0) { 1451 zerror("invalid END header (bad central directory offset)"); 1452 } 1453 // read in the CEN and END 1454 cen = new byte[(int)(end.cenlen + ENDHDR)]; 1455 if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) { 1456 zerror("read CEN tables failed"); 1457 } 1458 total = end.centot; 1459 } else { 1460 total = knownTotal; 1461 } 1462 // hash table for entries 1463 entries = new int[total * 3]; 1464 tablelen = ((total/2) | 1); // Odd -> fewer collisions 1465 table = new int[tablelen]; 1466 Arrays.fill(table, ZIP_ENDCHAIN); 1467 int idx = 0; 1468 int hash = 0; 1469 int next = -1; 1470 1471 // list for all meta entries 1472 ArrayList<Integer> metanamesList = null; 1473 1474 // Iterate through the entries in the central directory 1475 int i = 0; 1476 int hsh = 0; 1477 int pos = 0; 1478 int limit = cen.length - ENDHDR; 1479 while (pos + CENHDR <= limit) { 1480 if (i >= total) { 1481 // This will only happen if the zip file has an incorrect 1482 // ENDTOT field, which usually means it contains more than 1483 // 65535 entries. 1484 initCEN(countCENHeaders(cen, limit)); 1485 return; 1486 } 1487 if (CENSIG(cen, pos) != CENSIG) 1488 zerror("invalid CEN header (bad signature)"); 1489 int method = CENHOW(cen, pos); 1490 int nlen = CENNAM(cen, pos); 1491 int elen = CENEXT(cen, pos); 1492 int clen = CENCOM(cen, pos); 1493 if ((CENFLG(cen, pos) & 1) != 0) 1494 zerror("invalid CEN header (encrypted entry)"); 1495 if (method != STORED && method != DEFLATED) 1496 zerror("invalid CEN header (bad compression method: " + method + ")"); 1497 if (pos + CENHDR + nlen > limit) 1498 zerror("invalid CEN header (bad header size)"); 1499 // Record the CEN offset and the name hash in our hash cell. 1500 hash = hashN(cen, pos + CENHDR, nlen); 1501 hsh = (hash & 0x7fffffff) % tablelen; 1502 next = table[hsh]; 1503 table[hsh] = idx; 1504 idx = addEntry(idx, hash, next, pos); 1505 // Adds name to metanames. 1506 if (isMetaName(cen, pos + CENHDR, nlen)) { 1507 if (metanamesList == null) 1508 metanamesList = new ArrayList<>(4); 1509 metanamesList.add(pos); 1510 } 1511 // skip ext and comment 1512 pos += (CENHDR + nlen + elen + clen); 1513 i++; 1514 } 1515 total = i; 1516 if (metanamesList != null) { 1517 metanames = new int[metanamesList.size()]; 1518 for (int j = 0, len = metanames.length; j < len; j++) { 1519 metanames[j] = metanamesList.get(j); 1520 } 1521 } 1522 if (pos + ENDHDR != cen.length) { 1523 zerror("invalid CEN header (bad header size)"); 1524 } 1525 } 1526 1527 private static void zerror(String msg) throws ZipException { 1528 throw new ZipException(msg); 1529 } 1530 1531 /* 1532 * Returns the {@code pos} of the zip cen entry corresponding to the 1533 * specified entry name, or -1 if not found. 1534 */ 1535 private int getEntryPos(byte[] name, boolean addSlash) { 1536 if (total == 0) { 1537 return -1; 1538 } 1539 int hsh = hashN(name, 0, name.length); 1540 int idx = table[(hsh & 0x7fffffff) % tablelen]; 1541 /* 1542 * This while loop is an optimization where a double lookup 1543 * for name and name+/ is being performed. The name char 1544 * array has enough room at the end to try again with a 1545 * slash appended if the first table lookup does not succeed. 1546 */ 1547 while(true) { 1548 /* 1549 * Search down the target hash chain for a entry whose 1550 * 32 bit hash matches the hashed name. 1551 */ 1552 while (idx != ZIP_ENDCHAIN) { 1553 if (getEntryHash(idx) == hsh) { 1554 // The CEN name must match the specfied one 1555 int pos = getEntryPos(idx); 1556 if (name.length == CENNAM(cen, pos)) { 1557 boolean matched = true; 1558 int nameoff = pos + CENHDR; 1559 for (int i = 0; i < name.length; i++) { 1560 if (name[i] != cen[nameoff++]) { 1561 matched = false; 1562 break; 1563 } 1564 } 1565 if (matched) { 1566 return pos; 1567 } 1568 } 1569 } 1570 idx = getEntryNext(idx); 1571 } 1572 /* If not addSlash, or slash is already there, we are done */ 1573 if (!addSlash || name.length == 0 || name[name.length - 1] == '/') { 1574 return -1; 1575 } 1576 /* Add slash and try once more */ 1577 name = Arrays.copyOf(name, name.length + 1); 1578 name[name.length - 1] = '/'; 1579 hsh = hash_append(hsh, (byte)'/'); 1580 //idx = table[hsh % tablelen]; 1581 idx = table[(hsh & 0x7fffffff) % tablelen]; 1582 addSlash = false; 1583 } 1584 } 1585 1586 /** 1587 * Returns true if the bytes represent a non-directory name 1588 * beginning with "META-INF/", disregarding ASCII case. 1589 */ 1590 private static boolean isMetaName(byte[] name, int off, int len) { 1591 // Use the "oldest ASCII trick in the book" 1592 return len > 9 // "META-INF/".length() 1593 && name[off + len - 1] != '/' // non-directory 1594 && (name[off++] | 0x20) == 'm' 1595 && (name[off++] | 0x20) == 'e' 1596 && (name[off++] | 0x20) == 't' 1597 && (name[off++] | 0x20) == 'a' 1598 && (name[off++] ) == '-' 1599 && (name[off++] | 0x20) == 'i' 1600 && (name[off++] | 0x20) == 'n' 1601 && (name[off++] | 0x20) == 'f' 1602 && (name[off] ) == '/'; 1603 } 1604 1605 /** 1606 * Returns the number of CEN headers in a central directory. 1607 * Will not throw, even if the zip file is corrupt. 1608 * 1609 * @param cen copy of the bytes in a zip file's central directory 1610 * @param size number of bytes in central directory 1611 */ 1612 private static int countCENHeaders(byte[] cen, int size) { 1613 int count = 0; 1614 for (int p = 0; 1615 p + CENHDR <= size; 1616 p += CENHDR + CENNAM(cen, p) + CENEXT(cen, p) + CENCOM(cen, p)) 1617 count++; 1618 return count; 1619 } 1620 } 1621 }