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