1 /*
   2  * Copyright (c) 2009, 2020, 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 jdk.nio.zipfs;
  27 
  28 import java.io.BufferedOutputStream;
  29 import java.io.ByteArrayInputStream;
  30 import java.io.ByteArrayOutputStream;
  31 import java.io.EOFException;
  32 import java.io.FilterOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.OutputStream;
  36 import java.lang.Runtime.Version;
  37 import java.nio.ByteBuffer;
  38 import java.nio.MappedByteBuffer;
  39 import java.nio.channels.FileChannel;
  40 import java.nio.channels.FileLock;
  41 import java.nio.channels.ReadableByteChannel;
  42 import java.nio.channels.SeekableByteChannel;
  43 import java.nio.channels.WritableByteChannel;
  44 import java.nio.file.*;
  45 import java.nio.file.attribute.*;
  46 import java.nio.file.spi.FileSystemProvider;
  47 import java.security.AccessController;
  48 import java.security.PrivilegedAction;
  49 import java.security.PrivilegedActionException;
  50 import java.security.PrivilegedExceptionAction;
  51 import java.util.*;
  52 import java.util.concurrent.locks.ReadWriteLock;
  53 import java.util.concurrent.locks.ReentrantReadWriteLock;
  54 import java.util.function.Consumer;
  55 import java.util.function.Function;
  56 import java.util.jar.Attributes;
  57 import java.util.jar.Manifest;
  58 import java.util.regex.Pattern;
  59 import java.util.zip.CRC32;
  60 import java.util.zip.Deflater;
  61 import java.util.zip.DeflaterOutputStream;
  62 import java.util.zip.Inflater;
  63 import java.util.zip.InflaterInputStream;
  64 import java.util.zip.ZipException;
  65 
  66 import static java.lang.Boolean.TRUE;
  67 import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
  68 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
  69 import static java.nio.file.StandardOpenOption.APPEND;
  70 import static java.nio.file.StandardOpenOption.CREATE;
  71 import static java.nio.file.StandardOpenOption.CREATE_NEW;
  72 import static java.nio.file.StandardOpenOption.READ;
  73 import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
  74 import static java.nio.file.StandardOpenOption.WRITE;
  75 import static jdk.nio.zipfs.ZipConstants.*;
  76 import static jdk.nio.zipfs.ZipUtils.*;
  77 
  78 /**
  79  * A FileSystem built on a zip file
  80  *
  81  * @author Xueming Shen
  82  */
  83 class ZipFileSystem extends FileSystem {
  84     // statics
  85     private static final boolean isWindows = AccessController.doPrivileged(
  86         (PrivilegedAction<Boolean>)()->System.getProperty("os.name")
  87                                              .startsWith("Windows"));
  88     private static final byte[] ROOTPATH = new byte[] { '/' };
  89     private static final String PROPERTY_POSIX = "enablePosixFileAttributes";
  90     private static final String PROPERTY_DEFAULT_OWNER = "defaultOwner";
  91     private static final String PROPERTY_DEFAULT_GROUP = "defaultGroup";
  92     private static final String PROPERTY_DEFAULT_PERMISSIONS = "defaultPermissions";
  93     // Property used to specify the entry version to use for a multi-release JAR
  94     private static final String PROPERTY_RELEASE_VERSION = "releaseVersion";
  95     // Original property used to specify the entry version to use for a
  96     // multi-release JAR which is kept for backwards compatibility.
  97     private static final String PROPERTY_MULTI_RELEASE = "multi-release";
  98 
  99     private static final Set<PosixFilePermission> DEFAULT_PERMISSIONS =
 100         PosixFilePermissions.fromString("rwxrwxrwx");
 101     // Property used to specify the compression mode to use
 102     private static final String PROPERTY_COMPRESSION_METHOD = "compressionMethod";
 103     // Value specified for compressionMethod property to compress Zip entries
 104     private static final String COMPRESSION_METHOD_DEFLATED = "DEFLATED";
 105     // Value specified for compressionMethod property to not compress Zip entries
 106     private static final String COMPRESSION_METHOD_STORED = "STORED";
 107 
 108     private final ZipFileSystemProvider provider;
 109     private final Path zfpath;
 110     final ZipCoder zc;
 111     private final ZipPath rootdir;
 112     private boolean readOnly; // readonly file system, false by default
 113 
 114     // default time stamp for pseudo entries
 115     private final long zfsDefaultTimeStamp = System.currentTimeMillis();
 116 
 117     // configurable by env map
 118     private final boolean noExtt;        // see readExtra()
 119     private final boolean useTempFile;   // use a temp file for newOS, default
 120                                          // is to use BAOS for better performance
 121     private final boolean forceEnd64;
 122     private final int defaultCompressionMethod; // METHOD_STORED if "noCompression=true"
 123                                                 // METHOD_DEFLATED otherwise
 124 
 125     // entryLookup is identity by default, will be overridden for multi-release jars
 126     private Function<byte[], byte[]> entryLookup = Function.identity();
 127 
 128     // POSIX support
 129     final boolean supportPosix;
 130     private final UserPrincipal defaultOwner;
 131     private final GroupPrincipal defaultGroup;
 132     private final Set<PosixFilePermission> defaultPermissions;
 133 
 134     private final Set<String> supportedFileAttributeViews;
 135 
 136     ZipFileSystem(ZipFileSystemProvider provider,
 137                   Path zfpath,
 138                   Map<String, ?> env) throws IOException
 139     {
 140         // default encoding for name/comment
 141         String nameEncoding = env.containsKey("encoding") ?
 142             (String)env.get("encoding") : "UTF-8";
 143         this.noExtt = "false".equals(env.get("zipinfo-time"));
 144         this.useTempFile  = isTrue(env, "useTempFile");
 145         this.forceEnd64 = isTrue(env, "forceZIP64End");
 146         this.defaultCompressionMethod = getDefaultCompressionMethod(env);
 147         this.supportPosix = isTrue(env, PROPERTY_POSIX);
 148         this.defaultOwner = initOwner(zfpath, env);
 149         this.defaultGroup = initGroup(zfpath, env);
 150         this.defaultPermissions = initPermissions(env);
 151         this.supportedFileAttributeViews = supportPosix ?
 152             Set.of("basic", "posix", "zip") : Set.of("basic", "zip");
 153         if (Files.notExists(zfpath)) {
 154             // create a new zip if it doesn't exist
 155             if (isTrue(env, "create")) {
 156                 try (OutputStream os = Files.newOutputStream(zfpath, CREATE_NEW, WRITE)) {
 157                     new END().write(os, 0, forceEnd64);
 158                 }
 159             } else {
 160                 throw new NoSuchFileException(zfpath.toString());
 161             }
 162         }
 163         // sm and existence check
 164         zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.READ);
 165         boolean writeable = AccessController.doPrivileged(
 166             (PrivilegedAction<Boolean>)()->Files.isWritable(zfpath));
 167         this.readOnly = !writeable;
 168         this.zc = ZipCoder.get(nameEncoding);
 169         this.rootdir = new ZipPath(this, new byte[]{'/'});
 170         this.ch = Files.newByteChannel(zfpath, READ);
 171         try {
 172             this.cen = initCEN();
 173         } catch (IOException x) {
 174             try {
 175                 this.ch.close();
 176             } catch (IOException xx) {
 177                 x.addSuppressed(xx);
 178             }
 179             throw x;
 180         }
 181         this.provider = provider;
 182         this.zfpath = zfpath;
 183 
 184         initializeReleaseVersion(env);
 185     }
 186 
 187     /**
 188      * Return the compression method to use (STORED or DEFLATED).  If the
 189      * property {@code commpressionMethod} is set use its value to determine
 190      * the compression method to use.  If the property is not set, then the
 191      * default compression is DEFLATED unless the property {@code noCompression}
 192      * is set which is supported for backwards compatibility.
 193      * @param env Zip FS map of properties
 194      * @return The Compression method to use
 195      */
 196     private int getDefaultCompressionMethod(Map<String, ?> env) {
 197         int result =
 198                 isTrue(env, "noCompression") ? METHOD_STORED : METHOD_DEFLATED;
 199         if (env.containsKey(PROPERTY_COMPRESSION_METHOD)) {
 200             Object compressionMethod =  env.get(PROPERTY_COMPRESSION_METHOD);
 201             if (compressionMethod != null) {
 202                 if (compressionMethod instanceof String) {
 203                     switch (((String) compressionMethod).toUpperCase()) {
 204                         case COMPRESSION_METHOD_STORED:
 205                             result = METHOD_STORED;
 206                             break;
 207                         case COMPRESSION_METHOD_DEFLATED:
 208                             result = METHOD_DEFLATED;
 209                             break;
 210                         default:
 211                             throw new IllegalArgumentException(String.format(
 212                                     "The value for the %s property must be %s or %s",
 213                                     PROPERTY_COMPRESSION_METHOD, COMPRESSION_METHOD_STORED,
 214                                     COMPRESSION_METHOD_DEFLATED));
 215                     }
 216                 } else {
 217                     throw new IllegalArgumentException(String.format(
 218                             "The Object type for the %s property must be a String",
 219                             PROPERTY_COMPRESSION_METHOD));
 220                 }
 221             } else {
 222                 throw new IllegalArgumentException(String.format(
 223                         "The value for the %s property must be %s or %s",
 224                         PROPERTY_COMPRESSION_METHOD, COMPRESSION_METHOD_STORED,
 225                         COMPRESSION_METHOD_DEFLATED));
 226             }
 227         }
 228         return result;
 229     }
 230 
 231     // returns true if there is a name=true/"true" setting in env
 232     private static boolean isTrue(Map<String, ?> env, String name) {
 233         return "true".equals(env.get(name)) || TRUE.equals(env.get(name));
 234     }
 235 
 236     // Initialize the default owner for files inside the zip archive.
 237     // If not specified in env, it is the owner of the archive. If no owner can
 238     // be determined, we try to go with system property "user.name". If that's not
 239     // accessible, we return "<zipfs_default>".
 240     private UserPrincipal initOwner(Path zfpath, Map<String, ?> env) throws IOException {
 241         Object o = env.get(PROPERTY_DEFAULT_OWNER);
 242         if (o == null) {
 243             try {
 244                 PrivilegedExceptionAction<UserPrincipal> pa = ()->Files.getOwner(zfpath);
 245                 return AccessController.doPrivileged(pa);
 246             } catch (UnsupportedOperationException | PrivilegedActionException e) {
 247                 if (e instanceof UnsupportedOperationException ||
 248                     e.getCause() instanceof NoSuchFileException)
 249                 {
 250                     PrivilegedAction<String> pa = ()->System.getProperty("user.name");
 251                     String userName = AccessController.doPrivileged(pa);
 252                     return ()->userName;
 253                 } else {
 254                     throw new IOException(e);
 255                 }
 256             }
 257         }
 258         if (o instanceof String) {
 259             if (((String)o).isEmpty()) {
 260                 throw new IllegalArgumentException("Value for property " +
 261                         PROPERTY_DEFAULT_OWNER + " must not be empty.");
 262             }
 263             return ()->(String)o;
 264         }
 265         if (o instanceof UserPrincipal) {
 266             return (UserPrincipal)o;
 267         }
 268         throw new IllegalArgumentException("Value for property " +
 269                 PROPERTY_DEFAULT_OWNER + " must be of type " + String.class +
 270             " or " + UserPrincipal.class);
 271     }
 272 
 273     // Initialize the default group for files inside the zip archive.
 274     // If not specified in env, we try to determine the group of the zip archive itself.
 275     // If this is not possible/unsupported, we will return a group principal going by
 276     // the same name as the default owner.
 277     private GroupPrincipal initGroup(Path zfpath, Map<String, ?> env) throws IOException {
 278         Object o = env.get(PROPERTY_DEFAULT_GROUP);
 279         if (o == null) {
 280             try {
 281                 PosixFileAttributeView zfpv = Files.getFileAttributeView(zfpath, PosixFileAttributeView.class);
 282                 if (zfpv == null) {
 283                     return defaultOwner::getName;
 284                 }
 285                 PrivilegedExceptionAction<GroupPrincipal> pa = ()->zfpv.readAttributes().group();
 286                 return AccessController.doPrivileged(pa);
 287             } catch (UnsupportedOperationException | PrivilegedActionException e) {
 288                 if (e instanceof UnsupportedOperationException ||
 289                     e.getCause() instanceof NoSuchFileException)
 290                 {
 291                     return defaultOwner::getName;
 292                 } else {
 293                     throw new IOException(e);
 294                 }
 295             }
 296         }
 297         if (o instanceof String) {
 298             if (((String)o).isEmpty()) {
 299                 throw new IllegalArgumentException("Value for property " +
 300                         PROPERTY_DEFAULT_GROUP + " must not be empty.");
 301             }
 302             return ()->(String)o;
 303         }
 304         if (o instanceof GroupPrincipal) {
 305             return (GroupPrincipal)o;
 306         }
 307         throw new IllegalArgumentException("Value for property " +
 308                 PROPERTY_DEFAULT_GROUP + " must be of type " + String.class +
 309             " or " + GroupPrincipal.class);
 310     }
 311 
 312     // Initialize the default permissions for files inside the zip archive.
 313     // If not specified in env, it will return 777.
 314     private Set<PosixFilePermission> initPermissions(Map<String, ?> env) {
 315         Object o = env.get(PROPERTY_DEFAULT_PERMISSIONS);
 316         if (o == null) {
 317             return DEFAULT_PERMISSIONS;
 318         }
 319         if (o instanceof String) {
 320             return PosixFilePermissions.fromString((String)o);
 321         }
 322         if (!(o instanceof Set)) {
 323             throw new IllegalArgumentException("Value for property " +
 324                 PROPERTY_DEFAULT_PERMISSIONS + " must be of type " + String.class +
 325                 " or " + Set.class);
 326         }
 327         Set<PosixFilePermission> perms = new HashSet<>();
 328         for (Object o2 : (Set<?>)o) {
 329             if (o2 instanceof PosixFilePermission) {
 330                 perms.add((PosixFilePermission)o2);
 331             } else {
 332                 throw new IllegalArgumentException(PROPERTY_DEFAULT_PERMISSIONS +
 333                     " must only contain objects of type " + PosixFilePermission.class);
 334             }
 335         }
 336         return perms;
 337     }
 338 
 339     @Override
 340     public FileSystemProvider provider() {
 341         return provider;
 342     }
 343 
 344     @Override
 345     public String getSeparator() {
 346         return "/";
 347     }
 348 
 349     @Override
 350     public boolean isOpen() {
 351         return isOpen;
 352     }
 353 
 354     @Override
 355     public boolean isReadOnly() {
 356         return readOnly;
 357     }
 358 
 359     private void checkWritable() {
 360         if (readOnly) {
 361             throw new ReadOnlyFileSystemException();
 362         }
 363     }
 364 
 365     void setReadOnly() {
 366         this.readOnly = true;
 367     }
 368 
 369     @Override
 370     public Iterable<Path> getRootDirectories() {
 371         return List.of(rootdir);
 372     }
 373 
 374     ZipPath getRootDir() {
 375         return rootdir;
 376     }
 377 
 378     @Override
 379     public ZipPath getPath(String first, String... more) {
 380         if (more.length == 0) {
 381             return new ZipPath(this, first);
 382         }
 383         StringBuilder sb = new StringBuilder();
 384         sb.append(first);
 385         for (String path : more) {
 386             if (path.length() > 0) {
 387                 if (sb.length() > 0) {
 388                     sb.append('/');
 389                 }
 390                 sb.append(path);
 391             }
 392         }
 393         return new ZipPath(this, sb.toString());
 394     }
 395 
 396     @Override
 397     public UserPrincipalLookupService getUserPrincipalLookupService() {
 398         throw new UnsupportedOperationException();
 399     }
 400 
 401     @Override
 402     public WatchService newWatchService() {
 403         throw new UnsupportedOperationException();
 404     }
 405 
 406     FileStore getFileStore(ZipPath path) {
 407         return new ZipFileStore(path);
 408     }
 409 
 410     @Override
 411     public Iterable<FileStore> getFileStores() {
 412         return List.of(new ZipFileStore(rootdir));
 413     }
 414 
 415     @Override
 416     public Set<String> supportedFileAttributeViews() {
 417         return supportedFileAttributeViews;
 418     }
 419 
 420     @Override
 421     public String toString() {
 422         return zfpath.toString();
 423     }
 424 
 425     Path getZipFile() {
 426         return zfpath;
 427     }
 428 
 429     private static final String GLOB_SYNTAX = "glob";
 430     private static final String REGEX_SYNTAX = "regex";
 431 
 432     @Override
 433     public PathMatcher getPathMatcher(String syntaxAndInput) {
 434         int pos = syntaxAndInput.indexOf(':');
 435         if (pos <= 0 || pos == syntaxAndInput.length()) {
 436             throw new IllegalArgumentException();
 437         }
 438         String syntax = syntaxAndInput.substring(0, pos);
 439         String input = syntaxAndInput.substring(pos + 1);
 440         String expr;
 441         if (syntax.equalsIgnoreCase(GLOB_SYNTAX)) {
 442             expr = toRegexPattern(input);
 443         } else {
 444             if (syntax.equalsIgnoreCase(REGEX_SYNTAX)) {
 445                 expr = input;
 446             } else {
 447                 throw new UnsupportedOperationException("Syntax '" + syntax +
 448                     "' not recognized");
 449             }
 450         }
 451         // return matcher
 452         final Pattern pattern = Pattern.compile(expr);
 453         return (path)->pattern.matcher(path.toString()).matches();
 454     }
 455 
 456     @Override
 457     public void close() throws IOException {
 458         beginWrite();
 459         try {
 460             if (!isOpen)
 461                 return;
 462             isOpen = false;          // set closed
 463         } finally {
 464             endWrite();
 465         }
 466         if (!streams.isEmpty()) {    // unlock and close all remaining streams
 467             Set<InputStream> copy = new HashSet<>(streams);
 468             for (InputStream is : copy)
 469                 is.close();
 470         }
 471         beginWrite();                // lock and sync
 472         try {
 473             AccessController.doPrivileged((PrivilegedExceptionAction<Void>)() -> {
 474                 sync(); return null;
 475             });
 476             ch.close();              // close the ch just in case no update
 477                                      // and sync didn't close the ch
 478         } catch (PrivilegedActionException e) {
 479             throw (IOException)e.getException();
 480         } finally {
 481             endWrite();
 482         }
 483 
 484         synchronized (inflaters) {
 485             for (Inflater inf : inflaters)
 486                 inf.end();
 487         }
 488         synchronized (deflaters) {
 489             for (Deflater def : deflaters)
 490                 def.end();
 491         }
 492 
 493         beginWrite();                // lock and sync
 494         try {
 495             // Clear the map so that its keys & values can be garbage collected
 496             inodes = null;
 497         } finally {
 498             endWrite();
 499         }
 500 
 501         IOException ioe = null;
 502         synchronized (tmppaths) {
 503             for (Path p : tmppaths) {
 504                 try {
 505                     AccessController.doPrivileged(
 506                         (PrivilegedExceptionAction<Boolean>)() -> Files.deleteIfExists(p));
 507                 } catch (PrivilegedActionException e) {
 508                     IOException x = (IOException)e.getException();
 509                     if (ioe == null)
 510                         ioe = x;
 511                     else
 512                         ioe.addSuppressed(x);
 513                 }
 514             }
 515         }
 516         provider.removeFileSystem(zfpath, this);
 517         if (ioe != null)
 518            throw ioe;
 519     }
 520 
 521     ZipFileAttributes getFileAttributes(byte[] path)
 522         throws IOException
 523     {
 524         beginRead();
 525         try {
 526             ensureOpen();
 527             IndexNode inode = getInode(path);
 528             if (inode == null) {
 529                 return null;
 530             } else if (inode instanceof Entry) {
 531                 return (Entry)inode;
 532             } else if (inode.pos == -1) {
 533                 // pseudo directory, uses METHOD_STORED
 534                 Entry e = supportPosix ?
 535                     new PosixEntry(inode.name, inode.isdir, METHOD_STORED) :
 536                     new Entry(inode.name, inode.isdir, METHOD_STORED);
 537                 e.mtime = e.atime = e.ctime = zfsDefaultTimeStamp;
 538                 return e;
 539             } else {
 540                 return supportPosix ? new PosixEntry(this, inode) : new Entry(this, inode);
 541             }
 542         } finally {
 543             endRead();
 544         }
 545     }
 546 
 547     void checkAccess(byte[] path) throws IOException {
 548         beginRead();
 549         try {
 550             ensureOpen();
 551             // is it necessary to readCEN as a sanity check?
 552             if (getInode(path) == null) {
 553                 throw new NoSuchFileException(toString());
 554             }
 555 
 556         } finally {
 557             endRead();
 558         }
 559     }
 560 
 561     void setTimes(byte[] path, FileTime mtime, FileTime atime, FileTime ctime)
 562         throws IOException
 563     {
 564         checkWritable();
 565         beginWrite();
 566         try {
 567             ensureOpen();
 568             Entry e = getEntry(path);    // ensureOpen checked
 569             if (e == null)
 570                 throw new NoSuchFileException(getString(path));
 571             if (e.type == Entry.CEN)
 572                 e.type = Entry.COPY;     // copy e
 573             if (mtime != null)
 574                 e.mtime = mtime.toMillis();
 575             if (atime != null)
 576                 e.atime = atime.toMillis();
 577             if (ctime != null)
 578                 e.ctime = ctime.toMillis();
 579             update(e);
 580         } finally {
 581             endWrite();
 582         }
 583     }
 584 
 585     void setOwner(byte[] path, UserPrincipal owner) throws IOException {
 586         checkWritable();
 587         beginWrite();
 588         try {
 589             ensureOpen();
 590             Entry e = getEntry(path);    // ensureOpen checked
 591             if (e == null) {
 592                 throw new NoSuchFileException(getString(path));
 593             }
 594             // as the owner information is not persistent, we don't need to
 595             // change e.type to Entry.COPY
 596             if (e instanceof PosixEntry) {
 597                 ((PosixEntry)e).owner = owner;
 598                 update(e);
 599             }
 600         } finally {
 601             endWrite();
 602         }
 603     }
 604 
 605     void setGroup(byte[] path, GroupPrincipal group) throws IOException {
 606         checkWritable();
 607         beginWrite();
 608         try {
 609             ensureOpen();
 610             Entry e = getEntry(path);    // ensureOpen checked
 611             if (e == null) {
 612                 throw new NoSuchFileException(getString(path));
 613             }
 614             // as the group information is not persistent, we don't need to
 615             // change e.type to Entry.COPY
 616             if (e instanceof PosixEntry) {
 617                 ((PosixEntry)e).group = group;
 618                 update(e);
 619             }
 620         } finally {
 621             endWrite();
 622         }
 623     }
 624 
 625     void setPermissions(byte[] path, Set<PosixFilePermission> perms) throws IOException {
 626         checkWritable();
 627         beginWrite();
 628         try {
 629             ensureOpen();
 630             Entry e = getEntry(path);    // ensureOpen checked
 631             if (e == null) {
 632                 throw new NoSuchFileException(getString(path));
 633             }
 634             if (e.type == Entry.CEN) {
 635                 e.type = Entry.COPY;     // copy e
 636             }
 637             e.posixPerms = perms == null ? -1 : ZipUtils.permsToFlags(perms);
 638             update(e);
 639         } finally {
 640             endWrite();
 641         }
 642     }
 643 
 644     boolean exists(byte[] path) {
 645         beginRead();
 646         try {
 647             ensureOpen();
 648             return getInode(path) != null;
 649         } finally {
 650             endRead();
 651         }
 652     }
 653 
 654     boolean isDirectory(byte[] path) {
 655         beginRead();
 656         try {
 657             IndexNode n = getInode(path);
 658             return n != null && n.isDir();
 659         } finally {
 660             endRead();
 661         }
 662     }
 663 
 664     // returns the list of child paths of "path"
 665     Iterator<Path> iteratorOf(ZipPath dir,
 666                               DirectoryStream.Filter<? super Path> filter)
 667         throws IOException
 668     {
 669         beginWrite();    // iteration of inodes needs exclusive lock
 670         try {
 671             ensureOpen();
 672             byte[] path = dir.getResolvedPath();
 673             IndexNode inode = getInode(path);
 674             if (inode == null)
 675                 throw new NotDirectoryException(getString(path));
 676             List<Path> list = new ArrayList<>();
 677             IndexNode child = inode.child;
 678             while (child != null) {
 679                 // (1) Assume each path from the zip file itself is "normalized"
 680                 // (2) IndexNode.name is absolute. see IndexNode(byte[],int,int)
 681                 // (3) If parent "dir" is relative when ZipDirectoryStream
 682                 //     is created, the returned child path needs to be relative
 683                 //     as well.
 684                 ZipPath childPath = new ZipPath(this, child.name, true);
 685                 ZipPath childFileName = childPath.getFileName();
 686                 ZipPath zpath = dir.resolve(childFileName);
 687                 if (filter == null || filter.accept(zpath))
 688                     list.add(zpath);
 689                 child = child.sibling;
 690             }
 691             return list.iterator();
 692         } finally {
 693             endWrite();
 694         }
 695     }
 696 
 697     void createDirectory(byte[] dir, FileAttribute<?>... attrs) throws IOException {
 698         checkWritable();
 699         beginWrite();
 700         try {
 701             ensureOpen();
 702             if (dir.length == 0 || exists(dir))  // root dir, or existing dir
 703                 throw new FileAlreadyExistsException(getString(dir));
 704             checkParents(dir);
 705             Entry e = supportPosix ?
 706                 new PosixEntry(dir, Entry.NEW, true, METHOD_STORED, attrs) :
 707                 new Entry(dir, Entry.NEW, true, METHOD_STORED, attrs);
 708             update(e);
 709         } finally {
 710             endWrite();
 711         }
 712     }
 713 
 714     void copyFile(boolean deletesrc, byte[]src, byte[] dst, CopyOption... options)
 715         throws IOException
 716     {
 717         checkWritable();
 718         if (Arrays.equals(src, dst))
 719             return;    // do nothing, src and dst are the same
 720 
 721         beginWrite();
 722         try {
 723             ensureOpen();
 724             Entry eSrc = getEntry(src);  // ensureOpen checked
 725 
 726             if (eSrc == null)
 727                 throw new NoSuchFileException(getString(src));
 728             if (eSrc.isDir()) {    // spec says to create dst dir
 729                 createDirectory(dst);
 730                 return;
 731             }
 732             boolean hasReplace = false;
 733             boolean hasCopyAttrs = false;
 734             for (CopyOption opt : options) {
 735                 if (opt == REPLACE_EXISTING)
 736                     hasReplace = true;
 737                 else if (opt == COPY_ATTRIBUTES)
 738                     hasCopyAttrs = true;
 739             }
 740             Entry eDst = getEntry(dst);
 741             if (eDst != null) {
 742                 if (!hasReplace)
 743                     throw new FileAlreadyExistsException(getString(dst));
 744             } else {
 745                 checkParents(dst);
 746             }
 747             // copy eSrc entry and change name
 748             Entry u = supportPosix ?
 749                 new PosixEntry((PosixEntry)eSrc, Entry.COPY) :
 750                 new Entry(eSrc, Entry.COPY);
 751             u.name(dst);
 752             if (eSrc.type == Entry.NEW || eSrc.type == Entry.FILECH) {
 753                 u.type = eSrc.type;    // make it the same type
 754                 if (deletesrc) {       // if it's a "rename", take the data
 755                     u.bytes = eSrc.bytes;
 756                     u.file = eSrc.file;
 757                 } else {               // if it's not "rename", copy the data
 758                     if (eSrc.bytes != null)
 759                         u.bytes = Arrays.copyOf(eSrc.bytes, eSrc.bytes.length);
 760                     else if (eSrc.file != null) {
 761                         u.file = getTempPathForEntry(null);
 762                         Files.copy(eSrc.file, u.file, REPLACE_EXISTING);
 763                     }
 764                 }
 765             } else if (eSrc.type == Entry.CEN && eSrc.method != defaultCompressionMethod) {
 766 
 767                 /**
 768                  * We are copying a file within the same Zip file using a
 769                  * different compression method.
 770                  */
 771                 try (InputStream in = newInputStream(src);
 772                      OutputStream out = newOutputStream(dst,
 773                              CREATE, TRUNCATE_EXISTING, WRITE)) {
 774                     in.transferTo(out);
 775                 }
 776                 u = getEntry(dst);
 777             }
 778 
 779             if (!hasCopyAttrs)
 780                 u.mtime = u.atime= u.ctime = System.currentTimeMillis();
 781             update(u);
 782             if (deletesrc)
 783                 updateDelete(eSrc);
 784         } finally {
 785             endWrite();
 786         }
 787     }
 788 
 789     // Returns an output stream for writing the contents into the specified
 790     // entry.
 791     OutputStream newOutputStream(byte[] path, OpenOption... options)
 792         throws IOException
 793     {
 794         checkWritable();
 795         boolean hasCreateNew = false;
 796         boolean hasCreate = false;
 797         boolean hasAppend = false;
 798         boolean hasTruncate = false;
 799         for (OpenOption opt : options) {
 800             if (opt == READ)
 801                 throw new IllegalArgumentException("READ not allowed");
 802             if (opt == CREATE_NEW)
 803                 hasCreateNew = true;
 804             if (opt == CREATE)
 805                 hasCreate = true;
 806             if (opt == APPEND)
 807                 hasAppend = true;
 808             if (opt == TRUNCATE_EXISTING)
 809                 hasTruncate = true;
 810         }
 811         if (hasAppend && hasTruncate)
 812             throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
 813         beginRead();                 // only need a readlock, the "update()" will
 814         try {                        // try to obtain a writelock when the os is
 815             ensureOpen();            // being closed.
 816             Entry e = getEntry(path);
 817             if (e != null) {
 818                 if (e.isDir() || hasCreateNew)
 819                     throw new FileAlreadyExistsException(getString(path));
 820                 if (hasAppend) {
 821                     OutputStream os = getOutputStream(new Entry(e, Entry.NEW));
 822                     try (InputStream is = getInputStream(e)) {
 823                         is.transferTo(os);
 824                     }
 825                     return os;
 826                 }
 827                 return getOutputStream(supportPosix ?
 828                     new PosixEntry((PosixEntry)e, Entry.NEW, defaultCompressionMethod)
 829                         : new Entry(e, Entry.NEW, defaultCompressionMethod));
 830             } else {
 831                 if (!hasCreate && !hasCreateNew)
 832                     throw new NoSuchFileException(getString(path));
 833                 checkParents(path);
 834                 return getOutputStream(supportPosix ?
 835                     new PosixEntry(path, Entry.NEW, false, defaultCompressionMethod) :
 836                     new Entry(path, Entry.NEW, false, defaultCompressionMethod));
 837             }
 838         } finally {
 839             endRead();
 840         }
 841     }
 842 
 843     // Returns an input stream for reading the contents of the specified
 844     // file entry.
 845     InputStream newInputStream(byte[] path) throws IOException {
 846         beginRead();
 847         try {
 848             ensureOpen();
 849             Entry e = getEntry(path);
 850             if (e == null)
 851                 throw new NoSuchFileException(getString(path));
 852             if (e.isDir())
 853                 throw new FileSystemException(getString(path), "is a directory", null);
 854             return getInputStream(e);
 855         } finally {
 856             endRead();
 857         }
 858     }
 859 
 860     private void checkOptions(Set<? extends OpenOption> options) {
 861         // check for options of null type and option is an intance of StandardOpenOption
 862         for (OpenOption option : options) {
 863             if (option == null)
 864                 throw new NullPointerException();
 865             if (!(option instanceof StandardOpenOption))
 866                 throw new IllegalArgumentException();
 867         }
 868         if (options.contains(APPEND) && options.contains(TRUNCATE_EXISTING))
 869             throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
 870     }
 871 
 872     // Returns an output SeekableByteChannel for either
 873     // (1) writing the contents of a new entry, if the entry doesn't exist, or
 874     // (2) updating/replacing the contents of an existing entry.
 875     // Note: The content of the channel is not compressed until the
 876     // channel is closed
 877     private class EntryOutputChannel extends ByteArrayChannel {
 878         final Entry e;
 879 
 880         EntryOutputChannel(Entry e) {
 881             super(e.size > 0? (int)e.size : 8192, false);
 882             this.e = e;
 883             if (e.mtime == -1)
 884                 e.mtime = System.currentTimeMillis();
 885             if (e.method == -1)
 886                 e.method = defaultCompressionMethod;
 887             // store size, compressed size, and crc-32 in datadescriptor
 888             e.flag = FLAG_DATADESCR;
 889             if (zc.isUTF8())
 890                 e.flag |= FLAG_USE_UTF8;
 891         }
 892 
 893         @Override
 894         public void close() throws IOException {
 895             // will update the entry
 896             try (OutputStream os = getOutputStream(e)) {
 897                 os.write(toByteArray());
 898             }
 899             super.close();
 900         }
 901     }
 902 
 903     // Returns a Writable/ReadByteChannel for now. Might consider to use
 904     // newFileChannel() instead, which dump the entry data into a regular
 905     // file on the default file system and create a FileChannel on top of it.
 906     SeekableByteChannel newByteChannel(byte[] path,
 907                                        Set<? extends OpenOption> options,
 908                                        FileAttribute<?>... attrs)
 909         throws IOException
 910     {
 911         checkOptions(options);
 912         if (options.contains(StandardOpenOption.WRITE) ||
 913             options.contains(StandardOpenOption.APPEND)) {
 914             checkWritable();
 915             beginRead();    // only need a read lock, the "update()" will obtain
 916                             // the write lock when the channel is closed
 917             ensureOpen();
 918             try {
 919                 Entry e = getEntry(path);
 920                 if (e != null) {
 921                     if (e.isDir() || options.contains(CREATE_NEW))
 922                         throw new FileAlreadyExistsException(getString(path));
 923                     SeekableByteChannel sbc =
 924                             new EntryOutputChannel(supportPosix ?
 925                                 new PosixEntry((PosixEntry)e, Entry.NEW) :
 926                                 new Entry(e, Entry.NEW));
 927                     if (options.contains(APPEND)) {
 928                         try (InputStream is = getInputStream(e)) {  // copyover
 929                             byte[] buf = new byte[8192];
 930                             ByteBuffer bb = ByteBuffer.wrap(buf);
 931                             int n;
 932                             while ((n = is.read(buf)) != -1) {
 933                                 bb.position(0);
 934                                 bb.limit(n);
 935                                 sbc.write(bb);
 936                             }
 937                         }
 938                     }
 939                     return sbc;
 940                 }
 941                 if (!options.contains(CREATE) && !options.contains(CREATE_NEW))
 942                     throw new NoSuchFileException(getString(path));
 943                 checkParents(path);
 944                 return new EntryOutputChannel(
 945                     supportPosix ?
 946                         new PosixEntry(path, Entry.NEW, false, defaultCompressionMethod, attrs) :
 947                         new Entry(path, Entry.NEW, false, defaultCompressionMethod, attrs));
 948             } finally {
 949                 endRead();
 950             }
 951         } else {
 952             beginRead();
 953             try {
 954                 ensureOpen();
 955                 Entry e = getEntry(path);
 956                 if (e == null || e.isDir())
 957                     throw new NoSuchFileException(getString(path));
 958                 try (InputStream is = getInputStream(e)) {
 959                     // TBD: if (e.size < NNNNN);
 960                     return new ByteArrayChannel(is.readAllBytes(), true);
 961                 }
 962             } finally {
 963                 endRead();
 964             }
 965         }
 966     }
 967 
 968     // Returns a FileChannel of the specified entry.
 969     //
 970     // This implementation creates a temporary file on the default file system,
 971     // copy the entry data into it if the entry exists, and then create a
 972     // FileChannel on top of it.
 973     FileChannel newFileChannel(byte[] path,
 974                                Set<? extends OpenOption> options,
 975                                FileAttribute<?>... attrs)
 976         throws IOException
 977     {
 978         checkOptions(options);
 979         final  boolean forWrite = (options.contains(StandardOpenOption.WRITE) ||
 980                                    options.contains(StandardOpenOption.APPEND));
 981         beginRead();
 982         try {
 983             ensureOpen();
 984             Entry e = getEntry(path);
 985             if (forWrite) {
 986                 checkWritable();
 987                 if (e == null) {
 988                     if (!options.contains(StandardOpenOption.CREATE) &&
 989                         !options.contains(StandardOpenOption.CREATE_NEW)) {
 990                         throw new NoSuchFileException(getString(path));
 991                     }
 992                 } else {
 993                     if (options.contains(StandardOpenOption.CREATE_NEW)) {
 994                         throw new FileAlreadyExistsException(getString(path));
 995                     }
 996                     if (e.isDir())
 997                         throw new FileAlreadyExistsException("directory <"
 998                             + getString(path) + "> exists");
 999                 }
1000                 options = new HashSet<>(options);
1001                 options.remove(StandardOpenOption.CREATE_NEW); // for tmpfile
1002             } else if (e == null || e.isDir()) {
1003                 throw new NoSuchFileException(getString(path));
1004             }
1005 
1006             final boolean isFCH = (e != null && e.type == Entry.FILECH);
1007             final Path tmpfile = isFCH ? e.file : getTempPathForEntry(path);
1008             final FileChannel fch = tmpfile.getFileSystem()
1009                                            .provider()
1010                                            .newFileChannel(tmpfile, options, attrs);
1011             final Entry u = isFCH ? e : (
1012                 supportPosix ?
1013                 new PosixEntry(path, tmpfile, Entry.FILECH, attrs) :
1014                 new Entry(path, tmpfile, Entry.FILECH, attrs));
1015             if (forWrite) {
1016                 u.flag = FLAG_DATADESCR;
1017                 u.method = defaultCompressionMethod;
1018             }
1019             // is there a better way to hook into the FileChannel's close method?
1020             return new FileChannel() {
1021                 public int write(ByteBuffer src) throws IOException {
1022                     return fch.write(src);
1023                 }
1024                 public long write(ByteBuffer[] srcs, int offset, int length)
1025                     throws IOException
1026                 {
1027                     return fch.write(srcs, offset, length);
1028                 }
1029                 public long position() throws IOException {
1030                     return fch.position();
1031                 }
1032                 public FileChannel position(long newPosition)
1033                     throws IOException
1034                 {
1035                     fch.position(newPosition);
1036                     return this;
1037                 }
1038                 public long size() throws IOException {
1039                     return fch.size();
1040                 }
1041                 public FileChannel truncate(long size)
1042                     throws IOException
1043                 {
1044                     fch.truncate(size);
1045                     return this;
1046                 }
1047                 public void force(boolean metaData)
1048                     throws IOException
1049                 {
1050                     fch.force(metaData);
1051                 }
1052                 public long transferTo(long position, long count,
1053                                        WritableByteChannel target)
1054                     throws IOException
1055                 {
1056                     return fch.transferTo(position, count, target);
1057                 }
1058                 public long transferFrom(ReadableByteChannel src,
1059                                          long position, long count)
1060                     throws IOException
1061                 {
1062                     return fch.transferFrom(src, position, count);
1063                 }
1064                 public int read(ByteBuffer dst) throws IOException {
1065                     return fch.read(dst);
1066                 }
1067                 public int read(ByteBuffer dst, long position)
1068                     throws IOException
1069                 {
1070                     return fch.read(dst, position);
1071                 }
1072                 public long read(ByteBuffer[] dsts, int offset, int length)
1073                     throws IOException
1074                 {
1075                     return fch.read(dsts, offset, length);
1076                 }
1077                 public int write(ByteBuffer src, long position)
1078                     throws IOException
1079                 {
1080                    return fch.write(src, position);
1081                 }
1082                 public MappedByteBuffer map(MapMode mode,
1083                                             long position, long size)
1084                 {
1085                     throw new UnsupportedOperationException();
1086                 }
1087                 public FileLock lock(long position, long size, boolean shared)
1088                     throws IOException
1089                 {
1090                     return fch.lock(position, size, shared);
1091                 }
1092                 public FileLock tryLock(long position, long size, boolean shared)
1093                     throws IOException
1094                 {
1095                     return fch.tryLock(position, size, shared);
1096                 }
1097                 protected void implCloseChannel() throws IOException {
1098                     fch.close();
1099                     if (forWrite) {
1100                         u.mtime = System.currentTimeMillis();
1101                         u.size = Files.size(u.file);
1102                         update(u);
1103                     } else {
1104                         if (!isFCH)    // if this is a new fch for reading
1105                             removeTempPathForEntry(tmpfile);
1106                     }
1107                }
1108             };
1109         } finally {
1110             endRead();
1111         }
1112     }
1113 
1114     // the outstanding input streams that need to be closed
1115     private Set<InputStream> streams =
1116         Collections.synchronizedSet(new HashSet<>());
1117 
1118     private final Set<Path> tmppaths = Collections.synchronizedSet(new HashSet<>());
1119     private Path getTempPathForEntry(byte[] path) throws IOException {
1120         Path tmpPath = createTempFileInSameDirectoryAs(zfpath);
1121         if (path != null) {
1122             Entry e = getEntry(path);
1123             if (e != null) {
1124                 try (InputStream is = newInputStream(path)) {
1125                     Files.copy(is, tmpPath, REPLACE_EXISTING);
1126                 }
1127             }
1128         }
1129         return tmpPath;
1130     }
1131 
1132     private void removeTempPathForEntry(Path path) throws IOException {
1133         Files.delete(path);
1134         tmppaths.remove(path);
1135     }
1136 
1137     // check if all parents really exist. ZIP spec does not require
1138     // the existence of any "parent directory".
1139     private void checkParents(byte[] path) throws IOException {
1140         beginRead();
1141         try {
1142             while ((path = getParent(path)) != null &&
1143                     path != ROOTPATH) {
1144                 if (!inodes.containsKey(IndexNode.keyOf(path))) {
1145                     throw new NoSuchFileException(getString(path));
1146                 }
1147             }
1148         } finally {
1149             endRead();
1150         }
1151     }
1152 
1153     private static byte[] getParent(byte[] path) {
1154         int off = getParentOff(path);
1155         if (off <= 1)
1156             return ROOTPATH;
1157         return Arrays.copyOf(path, off);
1158     }
1159 
1160     private static int getParentOff(byte[] path) {
1161         int off = path.length - 1;
1162         if (off > 0 && path[off] == '/')  // isDirectory
1163             off--;
1164         while (off > 0 && path[off] != '/') { off--; }
1165         return off;
1166     }
1167 
1168     private void beginWrite() {
1169         rwlock.writeLock().lock();
1170     }
1171 
1172     private void endWrite() {
1173         rwlock.writeLock().unlock();
1174     }
1175 
1176     private void beginRead() {
1177         rwlock.readLock().lock();
1178     }
1179 
1180     private void endRead() {
1181         rwlock.readLock().unlock();
1182     }
1183 
1184     ///////////////////////////////////////////////////////////////////
1185 
1186     private volatile boolean isOpen = true;
1187     private final SeekableByteChannel ch; // channel to the zipfile
1188     final byte[]  cen;     // CEN & ENDHDR
1189     private END  end;
1190     private long locpos;   // position of first LOC header (usually 0)
1191 
1192     private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
1193 
1194     // name -> pos (in cen), IndexNode itself can be used as a "key"
1195     private LinkedHashMap<IndexNode, IndexNode> inodes;
1196 
1197     final byte[] getBytes(String name) {
1198         return zc.getBytes(name);
1199     }
1200 
1201     final String getString(byte[] name) {
1202         return zc.toString(name);
1203     }
1204 
1205     @SuppressWarnings("deprecation")
1206     protected void finalize() throws IOException {
1207         close();
1208     }
1209 
1210     // Reads len bytes of data from the specified offset into buf.
1211     // Returns the total number of bytes read.
1212     // Each/every byte read from here (except the cen, which is mapped).
1213     final long readFullyAt(byte[] buf, int off, long len, long pos)
1214         throws IOException
1215     {
1216         ByteBuffer bb = ByteBuffer.wrap(buf);
1217         bb.position(off);
1218         bb.limit((int)(off + len));
1219         return readFullyAt(bb, pos);
1220     }
1221 
1222     private long readFullyAt(ByteBuffer bb, long pos) throws IOException {
1223         synchronized(ch) {
1224             return ch.position(pos).read(bb);
1225         }
1226     }
1227 
1228     // Searches for end of central directory (END) header. The contents of
1229     // the END header will be read and placed in endbuf. Returns the file
1230     // position of the END header, otherwise returns -1 if the END header
1231     // was not found or an error occurred.
1232     private END findEND() throws IOException {
1233         byte[] buf = new byte[READBLOCKSZ];
1234         long ziplen = ch.size();
1235         long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
1236         long minPos = minHDR - (buf.length - ENDHDR);
1237 
1238         for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) {
1239             int off = 0;
1240             if (pos < 0) {
1241                 // Pretend there are some NUL bytes before start of file
1242                 off = (int)-pos;
1243                 Arrays.fill(buf, 0, off, (byte)0);
1244             }
1245             int len = buf.length - off;
1246             if (readFullyAt(buf, off, len, pos + off) != len)
1247                 throw new ZipException("zip END header not found");
1248 
1249             // Now scan the block backwards for END header signature
1250             for (int i = buf.length - ENDHDR; i >= 0; i--) {
1251                 if (buf[i]   == (byte)'P'    &&
1252                     buf[i+1] == (byte)'K'    &&
1253                     buf[i+2] == (byte)'\005' &&
1254                     buf[i+3] == (byte)'\006' &&
1255                     (pos + i + ENDHDR + ENDCOM(buf, i) == ziplen)) {
1256                     // Found END header
1257                     buf = Arrays.copyOfRange(buf, i, i + ENDHDR);
1258                     END end = new END();
1259                     // end.endsub = ENDSUB(buf); // not used
1260                     end.centot = ENDTOT(buf);
1261                     end.cenlen = ENDSIZ(buf);
1262                     end.cenoff = ENDOFF(buf);
1263                     // end.comlen = ENDCOM(buf); // not used
1264                     end.endpos = pos + i;
1265                     // try if there is zip64 end;
1266                     byte[] loc64 = new byte[ZIP64_LOCHDR];
1267                     if (end.endpos < ZIP64_LOCHDR ||
1268                         readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
1269                         != loc64.length ||
1270                         !locator64SigAt(loc64, 0)) {
1271                         return end;
1272                     }
1273                     long end64pos = ZIP64_LOCOFF(loc64);
1274                     byte[] end64buf = new byte[ZIP64_ENDHDR];
1275                     if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
1276                         != end64buf.length ||
1277                         !end64SigAt(end64buf, 0)) {
1278                         return end;
1279                     }
1280                     // end64 found,
1281                     long cenlen64 = ZIP64_ENDSIZ(end64buf);
1282                     long cenoff64 = ZIP64_ENDOFF(end64buf);
1283                     long centot64 = ZIP64_ENDTOT(end64buf);
1284                     // double-check
1285                     if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MINVAL ||
1286                         cenoff64 != end.cenoff && end.cenoff != ZIP64_MINVAL ||
1287                         centot64 != end.centot && end.centot != ZIP64_MINVAL32) {
1288                         return end;
1289                     }
1290                     // to use the end64 values
1291                     end.cenlen = cenlen64;
1292                     end.cenoff = cenoff64;
1293                     end.centot = (int)centot64; // assume total < 2g
1294                     end.endpos = end64pos;
1295                     return end;
1296                 }
1297             }
1298         }
1299         throw new ZipException("zip END header not found");
1300     }
1301 
1302     private void makeParentDirs(IndexNode node, IndexNode root) {
1303         IndexNode parent;
1304         ParentLookup lookup = new ParentLookup();
1305         while (true) {
1306             int off = getParentOff(node.name);
1307             // parent is root
1308             if (off <= 1) {
1309                 node.sibling = root.child;
1310                 root.child = node;
1311                 break;
1312             }
1313             // parent exists
1314             lookup = lookup.as(node.name, off);
1315             if (inodes.containsKey(lookup)) {
1316                 parent = inodes.get(lookup);
1317                 node.sibling = parent.child;
1318                 parent.child = node;
1319                 break;
1320             }
1321             // parent does not exist, add new pseudo directory entry
1322             parent = new IndexNode(Arrays.copyOf(node.name, off), true);
1323             inodes.put(parent, parent);
1324             node.sibling = parent.child;
1325             parent.child = node;
1326             node = parent;
1327         }
1328     }
1329 
1330     // ZIP directory has two issues:
1331     // (1) ZIP spec does not require the ZIP file to include
1332     //     directory entry
1333     // (2) all entries are not stored/organized in a "tree"
1334     //     structure.
1335     // A possible solution is to build the node tree ourself as
1336     // implemented below.
1337     private void buildNodeTree() {
1338         beginWrite();
1339         try {
1340             IndexNode root = inodes.remove(LOOKUPKEY.as(ROOTPATH));
1341             if (root == null) {
1342                 root = new IndexNode(ROOTPATH, true);
1343             }
1344             IndexNode[] nodes = inodes.values().toArray(new IndexNode[0]);
1345             inodes.put(root, root);
1346             for (IndexNode node : nodes) {
1347                 makeParentDirs(node, root);
1348             }
1349         } finally {
1350             endWrite();
1351         }
1352     }
1353 
1354     private void removeFromTree(IndexNode inode) {
1355         IndexNode parent = inodes.get(LOOKUPKEY.as(getParent(inode.name)));
1356         IndexNode child = parent.child;
1357         if (child.equals(inode)) {
1358             parent.child = child.sibling;
1359         } else {
1360             IndexNode last = child;
1361             while ((child = child.sibling) != null) {
1362                 if (child.equals(inode)) {
1363                     last.sibling = child.sibling;
1364                     break;
1365                 } else {
1366                     last = child;
1367                 }
1368             }
1369         }
1370     }
1371 
1372     /**
1373      * If a version property has been specified and the file represents a multi-release JAR,
1374      * determine the requested runtime version and initialize the ZipFileSystem instance accordingly.
1375      *
1376      * Checks if the Zip File System property "releaseVersion" has been specified. If it has,
1377      * use its value to determine the requested version. If not use the value of the "multi-release" property.
1378      */
1379     private void initializeReleaseVersion(Map<String, ?> env) throws IOException {
1380         Object o = env.containsKey(PROPERTY_RELEASE_VERSION) ?
1381             env.get(PROPERTY_RELEASE_VERSION) :
1382             env.get(PROPERTY_MULTI_RELEASE);
1383 
1384         if (o != null && isMultiReleaseJar()) {
1385             int version;
1386             if (o instanceof String) {
1387                 String s = (String)o;
1388                 if (s.equals("runtime")) {
1389                     version = Runtime.version().feature();
1390                 } else if (s.matches("^[1-9][0-9]*$")) {
1391                     version = Version.parse(s).feature();
1392                 } else {
1393                     throw new IllegalArgumentException("Invalid runtime version");
1394                 }
1395             } else if (o instanceof Integer) {
1396                 version = Version.parse(((Integer)o).toString()).feature();
1397             } else if (o instanceof Version) {
1398                 version = ((Version)o).feature();
1399             } else {
1400                 throw new IllegalArgumentException("env parameter must be String, " +
1401                     "Integer, or Version");
1402             }
1403             createVersionedLinks(version < 0 ? 0 : version);
1404             setReadOnly();
1405         }
1406     }
1407 
1408     /**
1409      * Returns true if the Manifest main attribute "Multi-Release" is set to true; false otherwise.
1410      */
1411     private boolean isMultiReleaseJar() throws IOException {
1412         try (InputStream is = newInputStream(getBytes("/META-INF/MANIFEST.MF"))) {
1413             String multiRelease = new Manifest(is).getMainAttributes()
1414                 .getValue(Attributes.Name.MULTI_RELEASE);
1415             return "true".equalsIgnoreCase(multiRelease);
1416         } catch (NoSuchFileException x) {
1417             return false;
1418         }
1419     }
1420 
1421     /**
1422      * Create a map of aliases for versioned entries, for example:
1423      *   version/PackagePrivate.class -> META-INF/versions/9/version/PackagePrivate.class
1424      *   version/PackagePrivate.java -> META-INF/versions/9/version/PackagePrivate.java
1425      *   version/Version.class -> META-INF/versions/10/version/Version.class
1426      *   version/Version.java -> META-INF/versions/10/version/Version.java
1427      *
1428      * Then wrap the map in a function that getEntry can use to override root
1429      * entry lookup for entries that have corresponding versioned entries.
1430      */
1431     private void createVersionedLinks(int version) {
1432         IndexNode verdir = getInode(getBytes("/META-INF/versions"));
1433         // nothing to do, if no /META-INF/versions
1434         if (verdir == null) {
1435             return;
1436         }
1437         // otherwise, create a map and for each META-INF/versions/{n} directory
1438         // put all the leaf inodes, i.e. entries, into the alias map
1439         // possibly shadowing lower versioned entries
1440         HashMap<IndexNode, byte[]> aliasMap = new HashMap<>();
1441         getVersionMap(version, verdir).values().forEach(versionNode ->
1442             walk(versionNode.child, entryNode ->
1443                 aliasMap.put(
1444                     getOrCreateInode(getRootName(entryNode, versionNode), entryNode.isdir),
1445                     entryNode.name))
1446         );
1447         entryLookup = path -> {
1448             byte[] entry = aliasMap.get(IndexNode.keyOf(path));
1449             return entry == null ? path : entry;
1450         };
1451     }
1452 
1453     /**
1454      * Create a sorted version map of version -> inode, for inodes <= max version.
1455      *   9 -> META-INF/versions/9
1456      *  10 -> META-INF/versions/10
1457      */
1458     private TreeMap<Integer, IndexNode> getVersionMap(int version, IndexNode metaInfVersions) {
1459         TreeMap<Integer,IndexNode> map = new TreeMap<>();
1460         IndexNode child = metaInfVersions.child;
1461         while (child != null) {
1462             Integer key = getVersion(child, metaInfVersions);
1463             if (key != null && key <= version) {
1464                 map.put(key, child);
1465             }
1466             child = child.sibling;
1467         }
1468         return map;
1469     }
1470 
1471     /**
1472      * Extract the integer version number -- META-INF/versions/9 returns 9.
1473      */
1474     private Integer getVersion(IndexNode inode, IndexNode metaInfVersions) {
1475         try {
1476             byte[] fullName = inode.name;
1477             return Integer.parseInt(getString(Arrays
1478                 .copyOfRange(fullName, metaInfVersions.name.length + 1, fullName.length)));
1479         } catch (NumberFormatException x) {
1480             // ignore this even though it might indicate issues with the JAR structure
1481             return null;
1482         }
1483     }
1484 
1485     /**
1486      * Walk the IndexNode tree processing all leaf nodes.
1487      */
1488     private void walk(IndexNode inode, Consumer<IndexNode> consumer) {
1489         if (inode == null) return;
1490         if (inode.isDir()) {
1491             walk(inode.child, consumer);
1492         } else {
1493             consumer.accept(inode);
1494         }
1495         walk(inode.sibling, consumer);
1496     }
1497 
1498     /**
1499      * Extract the root name from a versioned entry name.
1500      * E.g. given inode 'META-INF/versions/9/foo/bar.class'
1501      * and prefix 'META-INF/versions/9/' returns 'foo/bar.class'.
1502      */
1503     private byte[] getRootName(IndexNode inode, IndexNode prefix) {
1504         byte[] fullName = inode.name;
1505         return Arrays.copyOfRange(fullName, prefix.name.length, fullName.length);
1506     }
1507 
1508     // Reads zip file central directory. Returns the file position of first
1509     // CEN header, otherwise returns -1 if an error occurred. If zip->msg != NULL
1510     // then the error was a zip format error and zip->msg has the error text.
1511     // Always pass in -1 for knownTotal; it's used for a recursive call.
1512     private byte[] initCEN() throws IOException {
1513         end = findEND();
1514         if (end.endpos == 0) {
1515             inodes = new LinkedHashMap<>(10);
1516             locpos = 0;
1517             buildNodeTree();
1518             return null;         // only END header present
1519         }
1520         if (end.cenlen > end.endpos)
1521             throw new ZipException("invalid END header (bad central directory size)");
1522         long cenpos = end.endpos - end.cenlen;     // position of CEN table
1523 
1524         // Get position of first local file (LOC) header, taking into
1525         // account that there may be a stub prefixed to the zip file.
1526         locpos = cenpos - end.cenoff;
1527         if (locpos < 0)
1528             throw new ZipException("invalid END header (bad central directory offset)");
1529 
1530         // read in the CEN and END
1531         byte[] cen = new byte[(int)(end.cenlen + ENDHDR)];
1532         if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
1533             throw new ZipException("read CEN tables failed");
1534         }
1535         // Iterate through the entries in the central directory
1536         inodes = new LinkedHashMap<>(end.centot + 1);
1537         int pos = 0;
1538         int limit = cen.length - ENDHDR;
1539         while (pos < limit) {
1540             if (!cenSigAt(cen, pos))
1541                 throw new ZipException("invalid CEN header (bad signature)");
1542             int method = CENHOW(cen, pos);
1543             int nlen   = CENNAM(cen, pos);
1544             int elen   = CENEXT(cen, pos);
1545             int clen   = CENCOM(cen, pos);
1546             if ((CENFLG(cen, pos) & 1) != 0) {
1547                 throw new ZipException("invalid CEN header (encrypted entry)");
1548             }
1549             if (method != METHOD_STORED && method != METHOD_DEFLATED) {
1550                 throw new ZipException("invalid CEN header (unsupported compression method: " + method + ")");
1551             }
1552             if (pos + CENHDR + nlen > limit) {
1553                 throw new ZipException("invalid CEN header (bad header size)");
1554             }
1555             IndexNode inode = new IndexNode(cen, pos, nlen);
1556             inodes.put(inode, inode);
1557 
1558             // skip ext and comment
1559             pos += (CENHDR + nlen + elen + clen);
1560         }
1561         if (pos + ENDHDR != cen.length) {
1562             throw new ZipException("invalid CEN header (bad header size)");
1563         }
1564         buildNodeTree();
1565         return cen;
1566     }
1567 
1568     private void ensureOpen() {
1569         if (!isOpen)
1570             throw new ClosedFileSystemException();
1571     }
1572 
1573     // Creates a new empty temporary file in the same directory as the
1574     // specified file.  A variant of Files.createTempFile.
1575     private Path createTempFileInSameDirectoryAs(Path path) throws IOException {
1576         Path parent = path.toAbsolutePath().getParent();
1577         Path dir = (parent == null) ? path.getFileSystem().getPath(".") : parent;
1578         Path tmpPath = Files.createTempFile(dir, "zipfstmp", null);
1579         tmppaths.add(tmpPath);
1580         return tmpPath;
1581     }
1582 
1583     ////////////////////update & sync //////////////////////////////////////
1584 
1585     private boolean hasUpdate = false;
1586 
1587     // shared key. consumer guarantees the "writeLock" before use it.
1588     private final IndexNode LOOKUPKEY = new IndexNode(null, -1);
1589 
1590     private void updateDelete(IndexNode inode) {
1591         beginWrite();
1592         try {
1593             removeFromTree(inode);
1594             inodes.remove(inode);
1595             hasUpdate = true;
1596         } finally {
1597              endWrite();
1598         }
1599     }
1600 
1601     private void update(Entry e) {
1602         beginWrite();
1603         try {
1604             IndexNode old = inodes.put(e, e);
1605             if (old != null) {
1606                 removeFromTree(old);
1607             }
1608             if (e.type == Entry.NEW || e.type == Entry.FILECH || e.type == Entry.COPY) {
1609                 IndexNode parent = inodes.get(LOOKUPKEY.as(getParent(e.name)));
1610                 e.sibling = parent.child;
1611                 parent.child = e;
1612             }
1613             hasUpdate = true;
1614         } finally {
1615             endWrite();
1616         }
1617     }
1618 
1619     // copy over the whole LOC entry (header if necessary, data and ext) from
1620     // old zip to the new one.
1621     private long copyLOCEntry(Entry e, boolean updateHeader,
1622                               OutputStream os,
1623                               long written, byte[] buf)
1624         throws IOException
1625     {
1626         long locoff = e.locoff;  // where to read
1627         e.locoff = written;      // update the e.locoff with new value
1628 
1629         // calculate the size need to write out
1630         long size = 0;
1631         //  if there is A ext
1632         if ((e.flag & FLAG_DATADESCR) != 0) {
1633             if (e.size >= ZIP64_MINVAL || e.csize >= ZIP64_MINVAL)
1634                 size = 24;
1635             else
1636                 size = 16;
1637         }
1638         // read loc, use the original loc.elen/nlen
1639         //
1640         // an extra byte after loc is read, which should be the first byte of the
1641         // 'name' field of the loc. if this byte is '/', which means the original
1642         // entry has an absolute path in original zip/jar file, the e.writeLOC()
1643         // is used to output the loc, in which the leading "/" will be removed
1644         if (readFullyAt(buf, 0, LOCHDR + 1 , locoff) != LOCHDR + 1)
1645             throw new ZipException("loc: reading failed");
1646 
1647         if (updateHeader || LOCNAM(buf) > 0 && buf[LOCHDR] == '/') {
1648             locoff += LOCHDR + LOCNAM(buf) + LOCEXT(buf);  // skip header
1649             size += e.csize;
1650             written = e.writeLOC(os) + size;
1651         } else {
1652             os.write(buf, 0, LOCHDR);    // write out the loc header
1653             locoff += LOCHDR;
1654             // use e.csize,  LOCSIZ(buf) is zero if FLAG_DATADESCR is on
1655             // size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf);
1656             size += LOCNAM(buf) + LOCEXT(buf) + e.csize;
1657             written = LOCHDR + size;
1658         }
1659         int n;
1660         while (size > 0 &&
1661             (n = (int)readFullyAt(buf, 0, buf.length, locoff)) != -1)
1662         {
1663             if (size < n)
1664                 n = (int)size;
1665             os.write(buf, 0, n);
1666             size -= n;
1667             locoff += n;
1668         }
1669         return written;
1670     }
1671 
1672     private long writeEntry(Entry e, OutputStream os)
1673         throws IOException {
1674 
1675         if (e.bytes == null && e.file == null)    // dir, 0-length data
1676             return 0;
1677 
1678         long written = 0;
1679         if (e.method != METHOD_STORED && e.csize > 0 && (e.crc != 0 || e.size == 0)) {
1680             // pre-compressed entry, write directly to output stream
1681             writeTo(e, os);
1682         } else {
1683             try (OutputStream os2 = (e.method == METHOD_STORED) ?
1684                     new EntryOutputStreamCRC32(e, os) : new EntryOutputStreamDef(e, os)) {
1685                 writeTo(e, os2);
1686             }
1687         }
1688         written += e.csize;
1689         if ((e.flag & FLAG_DATADESCR) != 0) {
1690             written += e.writeEXT(os);
1691         }
1692         return written;
1693     }
1694 
1695     private void writeTo(Entry e, OutputStream os) throws IOException {
1696         if (e.bytes != null) {
1697             os.write(e.bytes, 0, e.bytes.length);
1698         } else if (e.file != null) {
1699             if (e.type == Entry.NEW || e.type == Entry.FILECH) {
1700                 try (InputStream is = Files.newInputStream(e.file)) {
1701                     is.transferTo(os);
1702                 }
1703             }
1704             Files.delete(e.file);
1705             tmppaths.remove(e.file);
1706         }
1707     }
1708 
1709     // sync the zip file system, if there is any update
1710     private void sync() throws IOException {
1711         if (!hasUpdate)
1712             return;
1713         PosixFileAttributes attrs = getPosixAttributes(zfpath);
1714         Path tmpFile = createTempFileInSameDirectoryAs(zfpath);
1715         try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(tmpFile, WRITE))) {
1716             ArrayList<Entry> elist = new ArrayList<>(inodes.size());
1717             long written = 0;
1718             byte[] buf = null;
1719             Entry e;
1720 





1721             // write loc
1722             for (IndexNode inode : inodes.values()) {




















1723                 if (inode instanceof Entry) {    // an updated inode
1724                     e = (Entry)inode;
1725                     try {
1726                         if (e.type == Entry.COPY) {
1727                             // entry copy: the only thing changed is the "name"
1728                             // and "nlen" in LOC header, so we update/rewrite the
1729                             // LOC in new file and simply copy the rest (data and
1730                             // ext) without enflating/deflating from the old zip
1731                             // file LOC entry.
1732                             if (buf == null)
1733                                 buf = new byte[8192];
1734                             written += copyLOCEntry(e, true, os, written, buf);
1735                         } else {                          // NEW, FILECH or CEN
1736                             e.locoff = written;
1737                             written += e.writeLOC(os);    // write loc header
1738                             written += writeEntry(e, os);
1739                         }
1740                         elist.add(e);
1741                     } catch (IOException x) {
1742                         x.printStackTrace();    // skip any in-accurate entry
1743                     }
1744                 } else {                        // unchanged inode
1745                     if (inode.pos == -1) {
1746                         continue;               // pseudo directory node
1747                     }
1748                     if (inode.name.length == 1 && inode.name[0] == '/') {
1749                         continue;               // no root '/' directory even if it
1750                                                 // exists in original zip/jar file.
1751                     }
1752                     e = supportPosix ? new PosixEntry(this, inode) : new Entry(this, inode);
1753                     try {
1754                         if (buf == null)
1755                             buf = new byte[8192];
1756                         written += copyLOCEntry(e, false, os, written, buf);
1757                         elist.add(e);
1758                     } catch (IOException x) {
1759                         x.printStackTrace();    // skip any wrong entry
1760                     }
1761                 }
1762             }
1763 
1764             // now write back the cen and end table
1765             end.cenoff = written;
1766             for (Entry entry : elist) {
1767                 written += entry.writeCEN(os);
1768             }
1769             end.centot = elist.size();
1770             end.cenlen = written - end.cenoff;
1771             end.write(os, written, forceEnd64);
1772         }
1773         ch.close();
1774         Files.delete(zfpath);
1775 
1776         // Set the POSIX permissions of the original Zip File if available
1777         // before moving the temp file
1778         if (attrs != null) {
1779             Files.setPosixFilePermissions(tmpFile, attrs.permissions());
1780         }
1781         Files.move(tmpFile, zfpath, REPLACE_EXISTING);
1782         hasUpdate = false;    // clear
1783     }
1784 
1785     /**
1786      * Returns a file's POSIX file attributes.
1787      * @param path The path to the file
1788      * @return The POSIX file attributes for the specified file or
1789      *         null if the POSIX attribute view is not available
1790      * @throws IOException If an error occurs obtaining the POSIX attributes for
1791      *                    the specified file
1792      */
1793     private PosixFileAttributes getPosixAttributes(Path path) throws IOException {
1794         try {
1795             PosixFileAttributeView view =
1796                     Files.getFileAttributeView(path, PosixFileAttributeView.class);
1797             // Return if the attribute view is not supported
1798             if (view == null) {
1799                 return null;
1800             }
1801             return view.readAttributes();
1802         } catch (UnsupportedOperationException e) {
1803             // PosixFileAttributes not available
1804             return null;
1805         }
1806     }
1807 
1808     private IndexNode getInode(byte[] path) {
1809         return inodes.get(IndexNode.keyOf(Objects.requireNonNull(entryLookup.apply(path), "path")));
1810     }
1811 
1812     /**
1813      * Return the IndexNode from the root tree. If it doesn't exist,
1814      * it gets created along with all parent directory IndexNodes.
1815      */
1816     private IndexNode getOrCreateInode(byte[] path, boolean isdir) {
1817         IndexNode node = getInode(path);
1818         // if node exists, return it
1819         if (node != null) {
1820             return node;
1821         }
1822 
1823         // otherwise create new pseudo node and parent directory hierarchy
1824         node = new IndexNode(path, isdir);
1825         beginWrite();
1826         try {
1827             makeParentDirs(node, Objects.requireNonNull(inodes.get(IndexNode.keyOf(ROOTPATH)), "no root node found"));
1828             return node;
1829         } finally {
1830             endWrite();
1831         }
1832     }
1833 
1834     private Entry getEntry(byte[] path) throws IOException {
1835         IndexNode inode = getInode(path);
1836         if (inode instanceof Entry)
1837             return (Entry)inode;
1838         if (inode == null || inode.pos == -1)
1839             return null;
1840         return supportPosix ? new PosixEntry(this, inode): new Entry(this, inode);
1841     }
1842 
1843     public void deleteFile(byte[] path, boolean failIfNotExists)
1844         throws IOException
1845     {
1846         checkWritable();
1847         IndexNode inode = getInode(path);
1848         if (inode == null) {
1849             if (path != null && path.length == 0)
1850                 throw new ZipException("root directory </> can't not be delete");
1851             if (failIfNotExists)
1852                 throw new NoSuchFileException(getString(path));
1853         } else {
1854             if (inode.isDir() && inode.child != null)
1855                 throw new DirectoryNotEmptyException(getString(path));
1856             updateDelete(inode);
1857         }
1858     }
1859 
1860     // Returns an out stream for either
1861     // (1) writing the contents of a new entry, if the entry exists, or
1862     // (2) updating/replacing the contents of the specified existing entry.
1863     private OutputStream getOutputStream(Entry e) throws IOException {
1864         if (e.mtime == -1)
1865             e.mtime = System.currentTimeMillis();
1866         if (e.method == -1)
1867             e.method = defaultCompressionMethod;
1868         // store size, compressed size, and crc-32 in datadescr
1869         e.flag = FLAG_DATADESCR;
1870         if (zc.isUTF8())
1871             e.flag |= FLAG_USE_UTF8;
1872         OutputStream os;
1873         if (useTempFile) {
1874             e.file = getTempPathForEntry(null);
1875             os = Files.newOutputStream(e.file, WRITE);
1876         } else {
1877             os = new ByteArrayOutputStream((e.size > 0)? (int)e.size : 8192);
1878         }
1879         if (e.method == METHOD_DEFLATED) {
1880             return new DeflatingEntryOutputStream(e, os);
1881         } else {
1882             return new EntryOutputStream(e, os);
1883         }
1884     }
1885 
1886     private class EntryOutputStream extends FilterOutputStream {
1887         private final Entry e;
1888         private long written;
1889         private boolean isClosed;
1890 
1891         EntryOutputStream(Entry e, OutputStream os) {
1892             super(os);
1893             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1894             // this.written = 0;
1895         }
1896 
1897         @Override
1898         public synchronized void write(int b) throws IOException {
1899             out.write(b);
1900             written += 1;
1901         }
1902 
1903         @Override
1904         public synchronized void write(byte[] b, int off, int len)
1905                 throws IOException {
1906             out.write(b, off, len);
1907             written += len;
1908         }
1909 
1910         @Override
1911         public synchronized void close() throws IOException {
1912             if (isClosed) {
1913                 return;
1914             }
1915             isClosed = true;
1916             e.size = written;
1917             if (out instanceof ByteArrayOutputStream)
1918                 e.bytes = ((ByteArrayOutputStream)out).toByteArray();
1919             super.close();
1920             update(e);
1921         }
1922     }
1923 
1924     // Output stream returned when writing "deflated" entries into memory,
1925     // to enable eager (possibly parallel) deflation and reduce memory required.
1926     private class DeflatingEntryOutputStream extends DeflaterOutputStream {
1927         private final CRC32 crc;
1928         private final Entry e;
1929         private boolean isClosed;
1930 
1931         DeflatingEntryOutputStream(Entry e, OutputStream os) {
1932             super(os, getDeflater());
1933             this.e = Objects.requireNonNull(e, "Zip entry is null");
1934             this.crc = new CRC32();
1935         }
1936 
1937         @Override
1938         public synchronized void write(byte[] b, int off, int len)
1939                 throws IOException {
1940             super.write(b, off, len);
1941             crc.update(b, off, len);
1942         }
1943 
1944         @Override
1945         public synchronized void close() throws IOException {
1946             if (isClosed)
1947                 return;
1948             isClosed = true;
1949             finish();
1950             e.size  = def.getBytesRead();
1951             e.csize = def.getBytesWritten();
1952             e.crc = crc.getValue();
1953             if (out instanceof ByteArrayOutputStream)
1954                 e.bytes = ((ByteArrayOutputStream)out).toByteArray();
1955             super.close();
1956             update(e);
1957             releaseDeflater(def);
1958         }
1959     }
1960 
1961     // Wrapper output stream class to write out a "stored" entry.
1962     // (1) this class does not close the underlying out stream when
1963     //     being closed.
1964     // (2) no need to be "synchronized", only used by sync()
1965     private class EntryOutputStreamCRC32 extends FilterOutputStream {
1966         private final CRC32 crc;
1967         private final Entry e;
1968         private long written;
1969         private boolean isClosed;
1970 
1971         EntryOutputStreamCRC32(Entry e, OutputStream os) {
1972             super(os);
1973             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1974             this.crc = new CRC32();
1975         }
1976 
1977         @Override
1978         public void write(int b) throws IOException {
1979             out.write(b);
1980             crc.update(b);
1981             written += 1;
1982         }
1983 
1984         @Override
1985         public void write(byte[] b, int off, int len)
1986                 throws IOException {
1987             out.write(b, off, len);
1988             crc.update(b, off, len);
1989             written += len;
1990         }
1991 
1992         @Override
1993         public void close() {
1994             if (isClosed)
1995                 return;
1996             isClosed = true;
1997             e.size = e.csize = written;
1998             e.crc = crc.getValue();
1999         }
2000     }
2001 
2002     // Wrapper output stream class to write out a "deflated" entry.
2003     // (1) this class does not close the underlying out stream when
2004     //     being closed.
2005     // (2) no need to be "synchronized", only used by sync()
2006     private class EntryOutputStreamDef extends DeflaterOutputStream {
2007         private final CRC32 crc;
2008         private final Entry e;
2009         private boolean isClosed;
2010 
2011         EntryOutputStreamDef(Entry e, OutputStream os) {
2012             super(os, getDeflater());
2013             this.e = Objects.requireNonNull(e, "Zip entry is null");
2014             this.crc = new CRC32();
2015         }
2016 
2017         @Override
2018         public void write(byte[] b, int off, int len) throws IOException {
2019             super.write(b, off, len);
2020             crc.update(b, off, len);
2021         }
2022 
2023         @Override
2024         public void close() throws IOException {
2025             if (isClosed)
2026                 return;
2027             isClosed = true;
2028             finish();
2029             e.size = def.getBytesRead();
2030             e.csize = def.getBytesWritten();
2031             e.crc = crc.getValue();
2032             releaseDeflater(def);
2033         }
2034     }
2035 
2036     private InputStream getInputStream(Entry e)
2037         throws IOException
2038     {
2039         InputStream eis;
2040         if (e.type == Entry.NEW) {
2041             if (e.bytes != null)
2042                 eis = new ByteArrayInputStream(e.bytes);
2043             else if (e.file != null)
2044                 eis = Files.newInputStream(e.file);
2045             else
2046                 throw new ZipException("update entry data is missing");
2047         } else if (e.type == Entry.FILECH) {
2048             // FILECH result is un-compressed.
2049             eis = Files.newInputStream(e.file);
2050             // TBD: wrap to hook close()
2051             // streams.add(eis);
2052             return eis;
2053         } else {  // untouched CEN or COPY
2054             eis = new EntryInputStream(e, ch);
2055         }
2056         if (e.method == METHOD_DEFLATED) {
2057             // MORE: Compute good size for inflater stream:
2058             long bufSize = e.size + 2; // Inflater likes a bit of slack
2059             if (bufSize > 65536)
2060                 bufSize = 8192;
2061             final long size = e.size;
2062             eis = new InflaterInputStream(eis, getInflater(), (int)bufSize) {
2063                 private boolean isClosed = false;
2064                 public void close() throws IOException {
2065                     if (!isClosed) {
2066                         releaseInflater(inf);
2067                         this.in.close();
2068                         isClosed = true;
2069                         streams.remove(this);
2070                     }
2071                 }
2072                 // Override fill() method to provide an extra "dummy" byte
2073                 // at the end of the input stream. This is required when
2074                 // using the "nowrap" Inflater option. (it appears the new
2075                 // zlib in 7 does not need it, but keep it for now)
2076                 protected void fill() throws IOException {
2077                     if (eof) {
2078                         throw new EOFException(
2079                             "Unexpected end of ZLIB input stream");
2080                     }
2081                     len = this.in.read(buf, 0, buf.length);
2082                     if (len == -1) {
2083                         buf[0] = 0;
2084                         len = 1;
2085                         eof = true;
2086                     }
2087                     inf.setInput(buf, 0, len);
2088                 }
2089                 private boolean eof;
2090 
2091                 public int available() {
2092                     if (isClosed)
2093                         return 0;
2094                     long avail = size - inf.getBytesWritten();
2095                     return avail > (long) Integer.MAX_VALUE ?
2096                         Integer.MAX_VALUE : (int) avail;
2097                 }
2098             };
2099         } else if (e.method == METHOD_STORED) {
2100             // TBD: wrap/ it does not seem necessary
2101         } else {
2102             throw new ZipException("invalid compression method");
2103         }
2104         streams.add(eis);
2105         return eis;
2106     }
2107 
2108     // Inner class implementing the input stream used to read
2109     // a (possibly compressed) zip file entry.
2110     private class EntryInputStream extends InputStream {
2111         private final SeekableByteChannel zfch; // local ref to zipfs's "ch". zipfs.ch might
2112                                                 // point to a new channel after sync()
2113         private long pos;                       // current position within entry data
2114         private long rem;                       // number of remaining bytes within entry
2115 
2116         EntryInputStream(Entry e, SeekableByteChannel zfch)
2117             throws IOException
2118         {
2119             this.zfch = zfch;
2120             rem = e.csize;
2121             pos = e.locoff;
2122             if (pos == -1) {
2123                 Entry e2 = getEntry(e.name);
2124                 if (e2 == null) {
2125                     throw new ZipException("invalid loc for entry <" + getString(e.name) + ">");
2126                 }
2127                 pos = e2.locoff;
2128             }
2129             pos = -pos;  // lazy initialize the real data offset
2130         }
2131 
2132         public int read(byte[] b, int off, int len) throws IOException {
2133             ensureOpen();
2134             initDataPos();
2135             if (rem == 0) {
2136                 return -1;
2137             }
2138             if (len <= 0) {
2139                 return 0;
2140             }
2141             if (len > rem) {
2142                 len = (int) rem;
2143             }
2144             // readFullyAt()
2145             long n;
2146             ByteBuffer bb = ByteBuffer.wrap(b);
2147             bb.position(off);
2148             bb.limit(off + len);
2149             synchronized(zfch) {
2150                 n = zfch.position(pos).read(bb);
2151             }
2152             if (n > 0) {
2153                 pos += n;
2154                 rem -= n;
2155             }
2156             if (rem == 0) {
2157                 close();
2158             }
2159             return (int)n;
2160         }
2161 
2162         public int read() throws IOException {
2163             byte[] b = new byte[1];
2164             if (read(b, 0, 1) == 1) {
2165                 return b[0] & 0xff;
2166             } else {
2167                 return -1;
2168             }
2169         }
2170 
2171         public long skip(long n) {
2172             ensureOpen();
2173             if (n > rem)
2174                 n = rem;
2175             pos += n;
2176             rem -= n;
2177             if (rem == 0) {
2178                 close();
2179             }
2180             return n;
2181         }
2182 
2183         public int available() {
2184             return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
2185         }
2186 
2187         public void close() {
2188             rem = 0;
2189             streams.remove(this);
2190         }
2191 
2192         private void initDataPos() throws IOException {
2193             if (pos <= 0) {
2194                 pos = -pos + locpos;
2195                 byte[] buf = new byte[LOCHDR];
2196                 if (readFullyAt(buf, 0, buf.length, pos) != LOCHDR) {
2197                     throw new ZipException("invalid loc " + pos + " for entry reading");
2198                 }
2199                 pos += LOCHDR + LOCNAM(buf) + LOCEXT(buf);
2200             }
2201         }
2202     }
2203 
2204     // Maxmum number of de/inflater we cache
2205     private final int MAX_FLATER = 20;
2206     // List of available Inflater objects for decompression
2207     private final List<Inflater> inflaters = new ArrayList<>();
2208 
2209     // Gets an inflater from the list of available inflaters or allocates
2210     // a new one.
2211     private Inflater getInflater() {
2212         synchronized (inflaters) {
2213             int size = inflaters.size();
2214             if (size > 0) {
2215                 return inflaters.remove(size - 1);
2216             } else {
2217                 return new Inflater(true);
2218             }
2219         }
2220     }
2221 
2222     // Releases the specified inflater to the list of available inflaters.
2223     private void releaseInflater(Inflater inf) {
2224         synchronized (inflaters) {
2225             if (inflaters.size() < MAX_FLATER) {
2226                 inf.reset();
2227                 inflaters.add(inf);
2228             } else {
2229                 inf.end();
2230             }
2231         }
2232     }
2233 
2234     // List of available Deflater objects for compression
2235     private final List<Deflater> deflaters = new ArrayList<>();
2236 
2237     // Gets a deflater from the list of available deflaters or allocates
2238     // a new one.
2239     private Deflater getDeflater() {
2240         synchronized (deflaters) {
2241             int size = deflaters.size();
2242             if (size > 0) {
2243                 return deflaters.remove(size - 1);
2244             } else {
2245                 return new Deflater(Deflater.DEFAULT_COMPRESSION, true);
2246             }
2247         }
2248     }
2249 
2250     // Releases the specified inflater to the list of available inflaters.
2251     private void releaseDeflater(Deflater def) {
2252         synchronized (deflaters) {
2253             if (deflaters.size() < MAX_FLATER) {
2254                def.reset();
2255                deflaters.add(def);
2256             } else {
2257                def.end();
2258             }
2259         }
2260     }
2261 
2262     // End of central directory record
2263     static class END {
2264         // The fields that are commented out below are not used by anyone and write() uses "0"
2265         // int  disknum;
2266         // int  sdisknum;
2267         // int  endsub;
2268         int  centot;        // 4 bytes
2269         long cenlen;        // 4 bytes
2270         long cenoff;        // 4 bytes
2271         // int  comlen;     // comment length
2272         // byte[] comment;
2273 
2274         // members of Zip64 end of central directory locator
2275         // int diskNum;
2276         long endpos;
2277         // int disktot;
2278 
2279         void write(OutputStream os, long offset, boolean forceEnd64) throws IOException {
2280             boolean hasZip64 = forceEnd64; // false;
2281             long xlen = cenlen;
2282             long xoff = cenoff;
2283             if (xlen >= ZIP64_MINVAL) {
2284                 xlen = ZIP64_MINVAL;
2285                 hasZip64 = true;
2286             }
2287             if (xoff >= ZIP64_MINVAL) {
2288                 xoff = ZIP64_MINVAL;
2289                 hasZip64 = true;
2290             }
2291             int count = centot;
2292             if (count >= ZIP64_MINVAL32) {
2293                 count = ZIP64_MINVAL32;
2294                 hasZip64 = true;
2295             }
2296             if (hasZip64) {
2297                 //zip64 end of central directory record
2298                 writeInt(os, ZIP64_ENDSIG);       // zip64 END record signature
2299                 writeLong(os, ZIP64_ENDHDR - 12); // size of zip64 end
2300                 writeShort(os, 45);               // version made by
2301                 writeShort(os, 45);               // version needed to extract
2302                 writeInt(os, 0);                  // number of this disk
2303                 writeInt(os, 0);                  // central directory start disk
2304                 writeLong(os, centot);            // number of directory entries on disk
2305                 writeLong(os, centot);            // number of directory entries
2306                 writeLong(os, cenlen);            // length of central directory
2307                 writeLong(os, cenoff);            // offset of central directory
2308 
2309                 //zip64 end of central directory locator
2310                 writeInt(os, ZIP64_LOCSIG);       // zip64 END locator signature
2311                 writeInt(os, 0);                  // zip64 END start disk
2312                 writeLong(os, offset);            // offset of zip64 END
2313                 writeInt(os, 1);                  // total number of disks (?)
2314             }
2315             writeInt(os, ENDSIG);                 // END record signature
2316             writeShort(os, 0);                    // number of this disk
2317             writeShort(os, 0);                    // central directory start disk
2318             writeShort(os, count);                // number of directory entries on disk
2319             writeShort(os, count);                // total number of directory entries
2320             writeInt(os, xlen);                   // length of central directory
2321             writeInt(os, xoff);                   // offset of central directory
2322             writeShort(os, 0);                    // zip file comment, not used
2323         }
2324     }
2325 
2326     // Internal node that links a "name" to its pos in cen table.
2327     // The node itself can be used as a "key" to lookup itself in
2328     // the HashMap inodes.
2329     static class IndexNode {
2330         byte[]  name;
2331         int     hashcode;    // node is hashable/hashed by its name
2332         boolean isdir;
2333         int     pos = -1;    // position in cen table, -1 means the
2334                              // entry does not exist in zip file
2335         IndexNode child;     // first child
2336         IndexNode sibling;   // next sibling
2337 
2338         IndexNode() {}
2339 
2340         IndexNode(byte[] name, boolean isdir) {
2341             name(name);
2342             this.isdir = isdir;
2343             this.pos = -1;
2344         }
2345 
2346         IndexNode(byte[] name, int pos) {
2347             name(name);
2348             this.pos = pos;
2349         }
2350 
2351         // constructor for initCEN() (1) remove trailing '/' (2) pad leading '/'
2352         IndexNode(byte[] cen, int pos, int nlen) {
2353             int noff = pos + CENHDR;
2354             if (cen[noff + nlen - 1] == '/') {
2355                 isdir = true;
2356                 nlen--;
2357             }
2358             if (nlen > 0 && cen[noff] == '/') {
2359                 name = Arrays.copyOfRange(cen, noff, noff + nlen);
2360             } else {
2361                 name = new byte[nlen + 1];
2362                 System.arraycopy(cen, noff, name, 1, nlen);
2363                 name[0] = '/';
2364             }
2365             name(normalize(name));
2366             this.pos = pos;
2367         }
2368 
2369         // Normalize the IndexNode.name field.
2370         private byte[] normalize(byte[] path) {
2371             int len = path.length;
2372             if (len == 0)
2373                 return path;
2374             byte prevC = 0;
2375             for (int pathPos = 0; pathPos < len; pathPos++) {
2376                 byte c = path[pathPos];
2377                 if (c == '/' && prevC == '/')
2378                     return normalize(path, pathPos - 1);
2379                 prevC = c;
2380             }
2381             if (len > 1 && prevC == '/') {
2382                 return Arrays.copyOf(path, len - 1);
2383             }
2384             return path;
2385         }
2386 
2387         private byte[] normalize(byte[] path, int off) {
2388             // As we know we have at least one / to trim, we can reduce
2389             // the size of the resulting array
2390             byte[] to = new byte[path.length - 1];
2391             int pathPos = 0;
2392             while (pathPos < off) {
2393                 to[pathPos] = path[pathPos];
2394                 pathPos++;
2395             }
2396             int toPos = pathPos;
2397             byte prevC = 0;
2398             while (pathPos < path.length) {
2399                 byte c = path[pathPos++];
2400                 if (c == '/' && prevC == '/')
2401                     continue;
2402                 to[toPos++] = c;
2403                 prevC = c;
2404             }
2405             if (toPos > 1 && to[toPos - 1] == '/')
2406                 toPos--;
2407             return (toPos == to.length) ? to : Arrays.copyOf(to, toPos);
2408         }
2409 
2410         private static final ThreadLocal<IndexNode> cachedKey = new ThreadLocal<>();
2411 
2412         static final IndexNode keyOf(byte[] name) { // get a lookup key;
2413             IndexNode key = cachedKey.get();
2414             if (key == null) {
2415                 key = new IndexNode(name, -1);
2416                 cachedKey.set(key);
2417             }
2418             return key.as(name);
2419         }
2420 
2421         final void name(byte[] name) {
2422             this.name = name;
2423             this.hashcode = Arrays.hashCode(name);
2424         }
2425 
2426         final IndexNode as(byte[] name) {           // reuse the node, mostly
2427             name(name);                             // as a lookup "key"
2428             return this;
2429         }
2430 
2431         boolean isDir() {
2432             return isdir;
2433         }
2434 
2435         @Override
2436         public boolean equals(Object other) {
2437             if (!(other instanceof IndexNode)) {
2438                 return false;
2439             }
2440             if (other instanceof ParentLookup) {
2441                 return ((ParentLookup)other).equals(this);
2442             }
2443             return Arrays.equals(name, ((IndexNode)other).name);
2444         }
2445 
2446         @Override
2447         public int hashCode() {
2448             return hashcode;
2449         }
2450 
2451         @Override
2452         public String toString() {
2453             return new String(name) + (isdir ? " (dir)" : " ") + ", index: " + pos;
2454         }
2455     }
2456 
2457     static class Entry extends IndexNode implements ZipFileAttributes {
2458         static final int CEN    = 1;  // entry read from cen
2459         static final int NEW    = 2;  // updated contents in bytes or file
2460         static final int FILECH = 3;  // fch update in "file"
2461         static final int COPY   = 4;  // copy of a CEN entry
2462 
2463         byte[] bytes;                 // updated content bytes
2464         Path   file;                  // use tmp file to store bytes;
2465         int    type = CEN;            // default is the entry read from cen
2466 
2467         // entry attributes
2468         int    version;
2469         int    flag;
2470         int    posixPerms = -1; // posix permissions
2471         int    method = -1;    // compression method
2472         long   mtime  = -1;    // last modification time (in DOS time)
2473         long   atime  = -1;    // last access time
2474         long   ctime  = -1;    // create time
2475         long   crc    = -1;    // crc-32 of entry data
2476         long   csize  = -1;    // compressed size of entry data
2477         long   size   = -1;    // uncompressed size of entry data
2478         byte[] extra;
2479 
2480         // CEN
2481         // The fields that are commented out below are not used by anyone and write() uses "0"
2482         // int    versionMade;
2483         // int    disk;
2484         // int    attrs;
2485         // long   attrsEx;
2486         long   locoff;
2487         byte[] comment;
2488 
2489         Entry(byte[] name, boolean isdir, int method) {
2490             name(name);
2491             this.isdir = isdir;
2492             this.mtime  = this.ctime = this.atime = System.currentTimeMillis();
2493             this.crc    = 0;
2494             this.size   = 0;
2495             this.csize  = 0;
2496             this.method = method;
2497         }
2498 
2499         @SuppressWarnings("unchecked")
2500         Entry(byte[] name, int type, boolean isdir, int method, FileAttribute<?>... attrs) {
2501             this(name, isdir, method);
2502             this.type = type;
2503             for (FileAttribute<?> attr : attrs) {
2504                 String attrName = attr.name();
2505                 if (attrName.equals("posix:permissions")) {
2506                     posixPerms = ZipUtils.permsToFlags((Set<PosixFilePermission>)attr.value());
2507                 }
2508             }
2509         }
2510 
2511         Entry(byte[] name, Path file, int type, FileAttribute<?>... attrs) {
2512             this(name, type, false, METHOD_STORED, attrs);
2513             this.file = file;
2514         }
2515 
2516         Entry(Entry e, int type, int compressionMethod) {
2517             this(e, type);
2518             this.method = compressionMethod;
2519         }
2520 
2521         Entry(Entry e, int type) {
2522             name(e.name);
2523             this.isdir     = e.isdir;
2524             this.version   = e.version;
2525             this.ctime     = e.ctime;
2526             this.atime     = e.atime;
2527             this.mtime     = e.mtime;
2528             this.crc       = e.crc;
2529             this.size      = e.size;
2530             this.csize     = e.csize;
2531             this.method    = e.method;
2532             this.extra     = e.extra;
2533             /*
2534             this.versionMade = e.versionMade;
2535             this.disk      = e.disk;
2536             this.attrs     = e.attrs;
2537             this.attrsEx   = e.attrsEx;
2538             */
2539             this.locoff    = e.locoff;
2540             this.comment   = e.comment;
2541             this.posixPerms = e.posixPerms;
2542             this.type      = type;
2543         }
2544 
2545         Entry(ZipFileSystem zipfs, IndexNode inode) throws IOException {
2546             readCEN(zipfs, inode);
2547         }
2548 
2549         // Calculates a suitable base for the version number to
2550         // be used for fields version made by/version needed to extract.
2551         // The lower bytes of these 2 byte fields hold the version number
2552         // (value/10 = major; value%10 = minor)
2553         // For different features certain minimum versions apply:
2554         // stored = 10 (1.0), deflated = 20 (2.0), zip64 = 45 (4.5)
2555         private int version(boolean zip64) throws ZipException {
2556             if (zip64) {
2557                 return 45;
2558             }
2559             if (method == METHOD_DEFLATED)
2560                 return 20;
2561             else if (method == METHOD_STORED)
2562                 return 10;
2563             throw new ZipException("unsupported compression method");
2564         }
2565 
2566         /**
2567          * Adds information about compatibility of file attribute information
2568          * to a version value.
2569          */
2570         private int versionMadeBy(int version) {
2571             return (posixPerms < 0) ? version :
2572                 VERSION_MADE_BY_BASE_UNIX | (version & 0xff);
2573         }
2574 
2575         ///////////////////// CEN //////////////////////
2576         private void readCEN(ZipFileSystem zipfs, IndexNode inode) throws IOException {
2577             byte[] cen = zipfs.cen;
2578             int pos = inode.pos;
2579             if (!cenSigAt(cen, pos))
2580                 throw new ZipException("invalid CEN header (bad signature)");
2581             version     = CENVER(cen, pos);
2582             flag        = CENFLG(cen, pos);
2583             method      = CENHOW(cen, pos);
2584             mtime       = dosToJavaTime(CENTIM(cen, pos));
2585             crc         = CENCRC(cen, pos);
2586             csize       = CENSIZ(cen, pos);
2587             size        = CENLEN(cen, pos);
2588             int nlen    = CENNAM(cen, pos);
2589             int elen    = CENEXT(cen, pos);
2590             int clen    = CENCOM(cen, pos);
2591             /*
2592             versionMade = CENVEM(cen, pos);
2593             disk        = CENDSK(cen, pos);
2594             attrs       = CENATT(cen, pos);
2595             attrsEx     = CENATX(cen, pos);
2596             */
2597             if (CENVEM_FA(cen, pos) == FILE_ATTRIBUTES_UNIX) {
2598                 posixPerms = CENATX_PERMS(cen, pos) & 0xFFF; // 12 bits for setuid, setgid, sticky + perms
2599             }
2600             locoff      = CENOFF(cen, pos);
2601             pos += CENHDR;
2602             this.name = inode.name;
2603             this.isdir = inode.isdir;
2604             this.hashcode = inode.hashcode;
2605 
2606             pos += nlen;
2607             if (elen > 0) {
2608                 extra = Arrays.copyOfRange(cen, pos, pos + elen);
2609                 pos += elen;
2610                 readExtra(zipfs);
2611             }
2612             if (clen > 0) {
2613                 comment = Arrays.copyOfRange(cen, pos, pos + clen);
2614             }
2615         }
2616 
2617         private int writeCEN(OutputStream os) throws IOException {
2618             long csize0  = csize;
2619             long size0   = size;
2620             long locoff0 = locoff;
2621             int elen64   = 0;                // extra for ZIP64
2622             int elenNTFS = 0;                // extra for NTFS (a/c/mtime)
2623             int elenEXTT = 0;                // extra for Extended Timestamp
2624             boolean foundExtraTime = false;  // if time stamp NTFS, EXTT present
2625 
2626             byte[] zname = isdir ? toDirectoryPath(name) : name;
2627 
2628             // confirm size/length
2629             int nlen = (zname != null) ? zname.length - 1 : 0;  // name has [0] as "slash"
2630             int elen = (extra != null) ? extra.length : 0;
2631             int eoff = 0;
2632             int clen = (comment != null) ? comment.length : 0;
2633             if (csize >= ZIP64_MINVAL) {
2634                 csize0 = ZIP64_MINVAL;
2635                 elen64 += 8;                 // csize(8)
2636             }
2637             if (size >= ZIP64_MINVAL) {
2638                 size0 = ZIP64_MINVAL;        // size(8)
2639                 elen64 += 8;
2640             }
2641             if (locoff >= ZIP64_MINVAL) {
2642                 locoff0 = ZIP64_MINVAL;
2643                 elen64 += 8;                 // offset(8)
2644             }
2645             if (elen64 != 0) {
2646                 elen64 += 4;                 // header and data sz 4 bytes
2647             }
2648             boolean zip64 = (elen64 != 0);
2649             int version0 = version(zip64);
2650             while (eoff + 4 < elen) {
2651                 int tag = SH(extra, eoff);
2652                 int sz = SH(extra, eoff + 2);
2653                 if (tag == EXTID_EXTT || tag == EXTID_NTFS) {
2654                     foundExtraTime = true;
2655                 }
2656                 eoff += (4 + sz);
2657             }
2658             if (!foundExtraTime) {
2659                 if (isWindows) {             // use NTFS
2660                     elenNTFS = 36;           // total 36 bytes
2661                 } else {                     // Extended Timestamp otherwise
2662                     elenEXTT = 9;            // only mtime in cen
2663                 }
2664             }
2665             writeInt(os, CENSIG);            // CEN header signature
2666             writeShort(os, versionMadeBy(version0)); // version made by
2667             writeShort(os, version0);        // version needed to extract
2668             writeShort(os, flag);            // general purpose bit flag
2669             writeShort(os, method);          // compression method
2670                                              // last modification time
2671             writeInt(os, (int)javaToDosTime(mtime));
2672             writeInt(os, crc);               // crc-32
2673             writeInt(os, csize0);            // compressed size
2674             writeInt(os, size0);             // uncompressed size
2675             writeShort(os, nlen);
2676             writeShort(os, elen + elen64 + elenNTFS + elenEXTT);
2677 
2678             if (comment != null) {
2679                 writeShort(os, Math.min(clen, 0xffff));
2680             } else {
2681                 writeShort(os, 0);
2682             }
2683             writeShort(os, 0);              // starting disk number
2684             writeShort(os, 0);              // internal file attributes (unused)
2685             writeInt(os, posixPerms > 0 ? posixPerms << 16 : 0); // external file
2686                                             // attributes, used for storing posix
2687                                             // permissions
2688             writeInt(os, locoff0);          // relative offset of local header
2689             writeBytes(os, zname, 1, nlen);
2690             if (zip64) {
2691                 writeShort(os, EXTID_ZIP64);// Zip64 extra
2692                 writeShort(os, elen64 - 4); // size of "this" extra block
2693                 if (size0 == ZIP64_MINVAL)
2694                     writeLong(os, size);
2695                 if (csize0 == ZIP64_MINVAL)
2696                     writeLong(os, csize);
2697                 if (locoff0 == ZIP64_MINVAL)
2698                     writeLong(os, locoff);
2699             }
2700             if (elenNTFS != 0) {
2701                 writeShort(os, EXTID_NTFS);
2702                 writeShort(os, elenNTFS - 4);
2703                 writeInt(os, 0);            // reserved
2704                 writeShort(os, 0x0001);     // NTFS attr tag
2705                 writeShort(os, 24);
2706                 writeLong(os, javaToWinTime(mtime));
2707                 writeLong(os, javaToWinTime(atime));
2708                 writeLong(os, javaToWinTime(ctime));
2709             }
2710             if (elenEXTT != 0) {
2711                 writeShort(os, EXTID_EXTT);
2712                 writeShort(os, elenEXTT - 4);
2713                 if (ctime == -1)
2714                     os.write(0x3);          // mtime and atime
2715                 else
2716                     os.write(0x7);          // mtime, atime and ctime
2717                 writeInt(os, javaToUnixTime(mtime));
2718             }
2719             if (extra != null)              // whatever not recognized
2720                 writeBytes(os, extra);
2721             if (comment != null)            //TBD: 0, Math.min(commentBytes.length, 0xffff));
2722                 writeBytes(os, comment);
2723             return CENHDR + nlen + elen + clen + elen64 + elenNTFS + elenEXTT;
2724         }
2725 
2726         ///////////////////// LOC //////////////////////
2727 
2728         private int writeLOC(OutputStream os) throws IOException {
2729             byte[] zname = isdir ? toDirectoryPath(name) : name;
2730             int nlen = (zname != null) ? zname.length - 1 : 0; // [0] is slash
2731             int elen = (extra != null) ? extra.length : 0;
2732             boolean foundExtraTime = false;     // if extra timestamp present
2733             int eoff = 0;
2734             int elen64 = 0;
2735             boolean zip64 = false;
2736             int elenEXTT = 0;
2737             int elenNTFS = 0;
2738             writeInt(os, LOCSIG);               // LOC header signature
2739             if ((flag & FLAG_DATADESCR) != 0) {
2740                 writeShort(os, version(false)); // version needed to extract
2741                 writeShort(os, flag);           // general purpose bit flag
2742                 writeShort(os, method);         // compression method
2743                 // last modification time
2744                 writeInt(os, (int)javaToDosTime(mtime));
2745                 // store size, uncompressed size, and crc-32 in data descriptor
2746                 // immediately following compressed entry data
2747                 writeInt(os, 0);
2748                 writeInt(os, 0);
2749                 writeInt(os, 0);
2750             } else {
2751                 if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) {
2752                     elen64 = 20;    //headid(2) + size(2) + size(8) + csize(8)
2753                     zip64 = true;
2754                 }
2755                 writeShort(os, version(zip64)); // version needed to extract
2756                 writeShort(os, flag);           // general purpose bit flag
2757                 writeShort(os, method);         // compression method
2758                                                 // last modification time
2759                 writeInt(os, (int)javaToDosTime(mtime));
2760                 writeInt(os, crc);              // crc-32
2761                 if (zip64) {
2762                     writeInt(os, ZIP64_MINVAL);
2763                     writeInt(os, ZIP64_MINVAL);
2764                 } else {
2765                     writeInt(os, csize);        // compressed size
2766                     writeInt(os, size);         // uncompressed size
2767                 }
2768             }
2769             while (eoff + 4 < elen) {
2770                 int tag = SH(extra, eoff);
2771                 int sz = SH(extra, eoff + 2);
2772                 if (tag == EXTID_EXTT || tag == EXTID_NTFS) {
2773                     foundExtraTime = true;
2774                 }
2775                 eoff += (4 + sz);
2776             }
2777             if (!foundExtraTime) {
2778                 if (isWindows) {
2779                     elenNTFS = 36;              // NTFS, total 36 bytes
2780                 } else {                        // on unix use "ext time"
2781                     elenEXTT = 9;
2782                     if (atime != -1)
2783                         elenEXTT += 4;
2784                     if (ctime != -1)
2785                         elenEXTT += 4;
2786                 }
2787             }
2788             writeShort(os, nlen);
2789             writeShort(os, elen + elen64 + elenNTFS + elenEXTT);
2790             writeBytes(os, zname, 1, nlen);
2791             if (zip64) {
2792                 writeShort(os, EXTID_ZIP64);
2793                 writeShort(os, 16);
2794                 writeLong(os, size);
2795                 writeLong(os, csize);
2796             }
2797             if (elenNTFS != 0) {
2798                 writeShort(os, EXTID_NTFS);
2799                 writeShort(os, elenNTFS - 4);
2800                 writeInt(os, 0);            // reserved
2801                 writeShort(os, 0x0001);     // NTFS attr tag
2802                 writeShort(os, 24);
2803                 writeLong(os, javaToWinTime(mtime));
2804                 writeLong(os, javaToWinTime(atime));
2805                 writeLong(os, javaToWinTime(ctime));
2806             }
2807             if (elenEXTT != 0) {
2808                 writeShort(os, EXTID_EXTT);
2809                 writeShort(os, elenEXTT - 4);// size for the folowing data block
2810                 int fbyte = 0x1;
2811                 if (atime != -1)           // mtime and atime
2812                     fbyte |= 0x2;
2813                 if (ctime != -1)           // mtime, atime and ctime
2814                     fbyte |= 0x4;
2815                 os.write(fbyte);           // flags byte
2816                 writeInt(os, javaToUnixTime(mtime));
2817                 if (atime != -1)
2818                     writeInt(os, javaToUnixTime(atime));
2819                 if (ctime != -1)
2820                     writeInt(os, javaToUnixTime(ctime));
2821             }
2822             if (extra != null) {
2823                 writeBytes(os, extra);
2824             }
2825             return LOCHDR + nlen + elen + elen64 + elenNTFS + elenEXTT;
2826         }
2827 
2828         // Data Descriptor
2829         private int writeEXT(OutputStream os) throws IOException {
2830             writeInt(os, EXTSIG);           // EXT header signature
2831             writeInt(os, crc);              // crc-32
2832             if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) {
2833                 writeLong(os, csize);
2834                 writeLong(os, size);
2835                 return 24;
2836             } else {
2837                 writeInt(os, csize);        // compressed size
2838                 writeInt(os, size);         // uncompressed size
2839                 return 16;
2840             }
2841         }
2842 
2843         // read NTFS, UNIX and ZIP64 data from cen.extra
2844         private void readExtra(ZipFileSystem zipfs) throws IOException {
2845             if (extra == null)
2846                 return;
2847             int elen = extra.length;
2848             int off = 0;
2849             int newOff = 0;
2850             while (off + 4 < elen) {
2851                 // extra spec: HeaderID+DataSize+Data
2852                 int pos = off;
2853                 int tag = SH(extra, pos);
2854                 int sz = SH(extra, pos + 2);
2855                 pos += 4;
2856                 if (pos + sz > elen)         // invalid data
2857                     break;
2858                 switch (tag) {
2859                 case EXTID_ZIP64 :
2860                     if (size == ZIP64_MINVAL) {
2861                         if (pos + 8 > elen)  // invalid zip64 extra
2862                             break;           // fields, just skip
2863                         size = LL(extra, pos);
2864                         pos += 8;
2865                     }
2866                     if (csize == ZIP64_MINVAL) {
2867                         if (pos + 8 > elen)
2868                             break;
2869                         csize = LL(extra, pos);
2870                         pos += 8;
2871                     }
2872                     if (locoff == ZIP64_MINVAL) {
2873                         if (pos + 8 > elen)
2874                             break;
2875                         locoff = LL(extra, pos);
2876                     }
2877                     break;
2878                 case EXTID_NTFS:
2879                     if (sz < 32)
2880                         break;
2881                     pos += 4;    // reserved 4 bytes
2882                     if (SH(extra, pos) !=  0x0001)
2883                         break;
2884                     if (SH(extra, pos + 2) != 24)
2885                         break;
2886                     // override the loc field, datatime here is
2887                     // more "accurate"
2888                     mtime  = winToJavaTime(LL(extra, pos + 4));
2889                     atime  = winToJavaTime(LL(extra, pos + 12));
2890                     ctime  = winToJavaTime(LL(extra, pos + 20));
2891                     break;
2892                 case EXTID_EXTT:
2893                     // spec says the Extened timestamp in cen only has mtime
2894                     // need to read the loc to get the extra a/ctime, if flag
2895                     // "zipinfo-time" is not specified to false;
2896                     // there is performance cost (move up to loc and read) to
2897                     // access the loc table foreach entry;
2898                     if (zipfs.noExtt) {
2899                         if (sz == 5)
2900                             mtime = unixToJavaTime(LG(extra, pos + 1));
2901                          break;
2902                     }
2903                     byte[] buf = new byte[LOCHDR];
2904                     if (zipfs.readFullyAt(buf, 0, buf.length , locoff)
2905                         != buf.length)
2906                         throw new ZipException("loc: reading failed");
2907                     if (!locSigAt(buf, 0))
2908                         throw new ZipException("loc: wrong sig ->"
2909                                            + Long.toString(getSig(buf, 0), 16));
2910                     int locElen = LOCEXT(buf);
2911                     if (locElen < 9)    // EXTT is at least 9 bytes
2912                         break;
2913                     int locNlen = LOCNAM(buf);
2914                     buf = new byte[locElen];
2915                     if (zipfs.readFullyAt(buf, 0, buf.length , locoff + LOCHDR + locNlen)
2916                         != buf.length)
2917                         throw new ZipException("loc extra: reading failed");
2918                     int locPos = 0;
2919                     while (locPos + 4 < buf.length) {
2920                         int locTag = SH(buf, locPos);
2921                         int locSZ  = SH(buf, locPos + 2);
2922                         locPos += 4;
2923                         if (locTag  != EXTID_EXTT) {
2924                             locPos += locSZ;
2925                              continue;
2926                         }
2927                         int end = locPos + locSZ - 4;
2928                         int flag = CH(buf, locPos++);
2929                         if ((flag & 0x1) != 0 && locPos <= end) {
2930                             mtime = unixToJavaTime(LG(buf, locPos));
2931                             locPos += 4;
2932                         }
2933                         if ((flag & 0x2) != 0 && locPos <= end) {
2934                             atime = unixToJavaTime(LG(buf, locPos));
2935                             locPos += 4;
2936                         }
2937                         if ((flag & 0x4) != 0 && locPos <= end) {
2938                             ctime = unixToJavaTime(LG(buf, locPos));
2939                         }
2940                         break;
2941                     }
2942                     break;
2943                 default:    // unknown tag
2944                     System.arraycopy(extra, off, extra, newOff, sz + 4);
2945                     newOff += (sz + 4);
2946                 }
2947                 off += (sz + 4);
2948             }
2949             if (newOff != 0 && newOff != extra.length)
2950                 extra = Arrays.copyOf(extra, newOff);
2951             else
2952                 extra = null;
2953         }
2954 
2955         @Override
2956         public String toString() {
2957             StringBuilder sb = new StringBuilder(1024);
2958             Formatter fm = new Formatter(sb);
2959             fm.format("    name            : %s%n", new String(name));
2960             fm.format("    creationTime    : %tc%n", creationTime().toMillis());
2961             fm.format("    lastAccessTime  : %tc%n", lastAccessTime().toMillis());
2962             fm.format("    lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
2963             fm.format("    isRegularFile   : %b%n", isRegularFile());
2964             fm.format("    isDirectory     : %b%n", isDirectory());
2965             fm.format("    isSymbolicLink  : %b%n", isSymbolicLink());
2966             fm.format("    isOther         : %b%n", isOther());
2967             fm.format("    fileKey         : %s%n", fileKey());
2968             fm.format("    size            : %d%n", size());
2969             fm.format("    compressedSize  : %d%n", compressedSize());
2970             fm.format("    crc             : %x%n", crc());
2971             fm.format("    method          : %d%n", method());
2972             Set<PosixFilePermission> permissions = storedPermissions().orElse(null);
2973             if (permissions != null) {
2974                 fm.format("    permissions     : %s%n", permissions);
2975             }
2976             fm.close();
2977             return sb.toString();
2978         }
2979 
2980         ///////// basic file attributes ///////////
2981         @Override
2982         public FileTime creationTime() {
2983             return FileTime.fromMillis(ctime == -1 ? mtime : ctime);
2984         }
2985 
2986         @Override
2987         public boolean isDirectory() {
2988             return isDir();
2989         }
2990 
2991         @Override
2992         public boolean isOther() {
2993             return false;
2994         }
2995 
2996         @Override
2997         public boolean isRegularFile() {
2998             return !isDir();
2999         }
3000 
3001         @Override
3002         public FileTime lastAccessTime() {
3003             return FileTime.fromMillis(atime == -1 ? mtime : atime);
3004         }
3005 
3006         @Override
3007         public FileTime lastModifiedTime() {
3008             return FileTime.fromMillis(mtime);
3009         }
3010 
3011         @Override
3012         public long size() {
3013             return size;
3014         }
3015 
3016         @Override
3017         public boolean isSymbolicLink() {
3018             return false;
3019         }
3020 
3021         @Override
3022         public Object fileKey() {
3023             return null;
3024         }
3025 
3026         ///////// zip file attributes ///////////
3027 
3028         @Override
3029         public long compressedSize() {
3030             return csize;
3031         }
3032 
3033         @Override
3034         public long crc() {
3035             return crc;
3036         }
3037 
3038         @Override
3039         public int method() {
3040             return method;
3041         }
3042 
3043         @Override
3044         public byte[] extra() {
3045             if (extra != null)
3046                 return Arrays.copyOf(extra, extra.length);
3047             return null;
3048         }
3049 
3050         @Override
3051         public byte[] comment() {
3052             if (comment != null)
3053                 return Arrays.copyOf(comment, comment.length);
3054             return null;
3055         }
3056 
3057         @Override
3058         public Optional<Set<PosixFilePermission>> storedPermissions() {
3059             Set<PosixFilePermission> perms = null;
3060             if (posixPerms != -1) {
3061                 perms = new HashSet<>(PosixFilePermission.values().length);
3062                 for (PosixFilePermission perm : PosixFilePermission.values()) {
3063                     if ((posixPerms & ZipUtils.permToFlag(perm)) != 0) {
3064                         perms.add(perm);
3065                     }
3066                 }
3067             }
3068             return Optional.ofNullable(perms);
3069         }
3070     }
3071 
3072     final class PosixEntry extends Entry implements PosixFileAttributes {
3073         private UserPrincipal owner = defaultOwner;
3074         private GroupPrincipal group = defaultGroup;
3075 
3076         PosixEntry(byte[] name, boolean isdir, int method) {
3077             super(name, isdir, method);
3078         }
3079 
3080         PosixEntry(byte[] name, int type, boolean isdir, int method, FileAttribute<?>... attrs) {
3081             super(name, type, isdir, method, attrs);
3082         }
3083 
3084         PosixEntry(byte[] name, Path file, int type, FileAttribute<?>... attrs) {
3085             super(name, file, type, attrs);
3086         }
3087 
3088         PosixEntry(PosixEntry e, int type, int compressionMethod) {
3089             super(e, type);
3090             this.method = compressionMethod;
3091         }
3092 
3093         PosixEntry(PosixEntry e, int type) {
3094             super(e, type);
3095             this.owner = e.owner;
3096             this.group = e.group;
3097         }
3098 
3099         PosixEntry(ZipFileSystem zipfs, IndexNode inode) throws IOException {
3100             super(zipfs, inode);
3101         }
3102 
3103         @Override
3104         public UserPrincipal owner() {
3105             return owner;
3106         }
3107 
3108         @Override
3109         public GroupPrincipal group() {
3110             return group;
3111         }
3112 
3113         @Override
3114         public Set<PosixFilePermission> permissions() {
3115             return storedPermissions().orElse(Set.copyOf(defaultPermissions));
3116         }
3117     }
3118 
3119     // purely for parent lookup, so we don't have to copy the parent
3120     // name every time
3121     static class ParentLookup extends IndexNode {
3122         int len;
3123         ParentLookup() {}
3124 
3125         final ParentLookup as(byte[] name, int len) { // as a lookup "key"
3126             name(name, len);
3127             return this;
3128         }
3129 
3130         void name(byte[] name, int len) {
3131             this.name = name;
3132             this.len = len;
3133             // calculate the hashcode the same way as Arrays.hashCode() does
3134             int result = 1;
3135             for (int i = 0; i < len; i++)
3136                 result = 31 * result + name[i];
3137             this.hashcode = result;
3138         }
3139 
3140         @Override
3141         public boolean equals(Object other) {
3142             if (!(other instanceof IndexNode)) {
3143                 return false;
3144             }
3145             byte[] oname = ((IndexNode)other).name;
3146             return Arrays.equals(name, 0, len,
3147                                  oname, 0, oname.length);
3148         }
3149     }
3150 }
--- EOF ---