1 /*
   2  * Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package 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.File;
  33 import java.io.FilterOutputStream;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.OutputStream;
  37 import java.nio.ByteBuffer;
  38 import java.nio.MappedByteBuffer;
  39 import java.nio.channels.*;
  40 import java.nio.file.*;
  41 import java.nio.file.attribute.*;
  42 import java.nio.file.spi.*;
  43 import java.security.AccessController;
  44 import java.security.PrivilegedAction;
  45 import java.security.PrivilegedActionException;
  46 import java.security.PrivilegedExceptionAction;
  47 import java.util.*;
  48 import java.util.concurrent.locks.ReadWriteLock;
  49 import java.util.concurrent.locks.ReentrantReadWriteLock;
  50 import java.util.regex.Pattern;
  51 import java.util.zip.CRC32;
  52 import java.util.zip.Inflater;
  53 import java.util.zip.Deflater;
  54 import java.util.zip.InflaterInputStream;
  55 import java.util.zip.DeflaterOutputStream;
  56 import java.util.zip.ZipException;
  57 import static java.lang.Boolean.*;
  58 import static jdk.nio.zipfs.ZipConstants.*;
  59 import static jdk.nio.zipfs.ZipUtils.*;
  60 import static java.nio.file.StandardOpenOption.*;
  61 import static java.nio.file.StandardCopyOption.*;
  62 
  63 /**
  64  * A FileSystem built on a zip file
  65  *
  66  * @author Xueming Shen
  67  */
  68 
  69 class ZipFileSystem extends FileSystem {
  70 
  71     private final ZipFileSystemProvider provider;
  72     private final Path zfpath;
  73     final ZipCoder zc;
  74     private final ZipPath rootdir;
  75     private boolean readOnly = false;    // readonly file system
  76 
  77     // configurable by env map
  78     private final boolean noExtt;        // see readExtra()
  79     private final boolean useTempFile;   // use a temp file for newOS, default
  80                                          // is to use BAOS for better performance
  81     private static final boolean isWindows = AccessController.doPrivileged(
  82             (PrivilegedAction<Boolean>) () -> System.getProperty("os.name")
  83                                                     .startsWith("Windows"));
  84     private final boolean forceEnd64;
  85     private final int defaultMethod;     // METHOD_STORED if "noCompression=true"
  86                                          // METHOD_DEFLATED otherwise
  87 
  88     ZipFileSystem(ZipFileSystemProvider provider,
  89                   Path zfpath,
  90                   Map<String, ?> env)  throws IOException
  91     {
  92         // default encoding for name/comment
  93         String nameEncoding = env.containsKey("encoding") ?
  94                               (String)env.get("encoding") : "UTF-8";
  95         this.noExtt = "false".equals(env.get("zipinfo-time"));
  96         this.useTempFile  = isTrue(env, "useTempFile");
  97         this.forceEnd64 = isTrue(env, "forceZIP64End");
  98         this.defaultMethod = isTrue(env, "noCompression") ? METHOD_STORED: METHOD_DEFLATED;
  99         if (Files.notExists(zfpath)) {
 100             // create a new zip if not exists
 101             if (isTrue(env, "create")) {
 102                 try (OutputStream os = Files.newOutputStream(zfpath, CREATE_NEW, WRITE)) {
 103                     new END().write(os, 0, forceEnd64);
 104                 }
 105             } else {
 106                 throw new FileSystemNotFoundException(zfpath.toString());
 107             }
 108         }
 109         // sm and existence check
 110         zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.READ);
 111         boolean writeable = AccessController.doPrivileged(
 112             (PrivilegedAction<Boolean>) () ->  Files.isWritable(zfpath));
 113         this.readOnly = !writeable;
 114         this.zc = ZipCoder.get(nameEncoding);
 115         this.rootdir = new ZipPath(this, new byte[]{'/'});
 116         this.ch = Files.newByteChannel(zfpath, READ);
 117         try {
 118             this.cen = initCEN();
 119         } catch (IOException x) {
 120             try {
 121                 this.ch.close();
 122             } catch (IOException xx) {
 123                 x.addSuppressed(xx);
 124             }
 125             throw x;
 126         }
 127         this.provider = provider;
 128         this.zfpath = zfpath;
 129     }
 130 
 131     // returns true if there is a name=true/"true" setting in env
 132     private static boolean isTrue(Map<String, ?> env, String name) {
 133         return "true".equals(env.get(name)) || TRUE.equals(env.get(name));
 134     }
 135 
 136     @Override
 137     public FileSystemProvider provider() {
 138         return provider;
 139     }
 140 
 141     @Override
 142     public String getSeparator() {
 143         return "/";
 144     }
 145 
 146     @Override
 147     public boolean isOpen() {
 148         return isOpen;
 149     }
 150 
 151     @Override
 152     public boolean isReadOnly() {
 153         return readOnly;
 154     }
 155 
 156     private void checkWritable() throws IOException {
 157         if (readOnly)
 158             throw new ReadOnlyFileSystemException();
 159     }
 160 
 161     void setReadOnly() {
 162         this.readOnly = true;
 163     }
 164 
 165     @Override
 166     public Iterable<Path> getRootDirectories() {
 167         return List.of(rootdir);
 168     }
 169 
 170     ZipPath getRootDir() {
 171         return rootdir;
 172     }
 173 
 174     @Override
 175     public ZipPath getPath(String first, String... more) {
 176         if (more.length == 0) {
 177             return new ZipPath(this, first);
 178         }
 179         StringBuilder sb = new StringBuilder();
 180         sb.append(first);
 181         for (String path : more) {
 182             if (path.length() > 0) {
 183                 if (sb.length() > 0) {
 184                     sb.append('/');
 185                 }
 186                 sb.append(path);
 187             }
 188         }
 189         return new ZipPath(this, sb.toString());
 190     }
 191 
 192     @Override
 193     public UserPrincipalLookupService getUserPrincipalLookupService() {
 194         throw new UnsupportedOperationException();
 195     }
 196 
 197     @Override
 198     public WatchService newWatchService() {
 199         throw new UnsupportedOperationException();
 200     }
 201 
 202     FileStore getFileStore(ZipPath path) {
 203         return new ZipFileStore(path);
 204     }
 205 
 206     @Override
 207     public Iterable<FileStore> getFileStores() {
 208         return List.of(new ZipFileStore(rootdir));
 209     }
 210 
 211     private static final Set<String> supportedFileAttributeViews =
 212             Set.of("basic", "zip");
 213 
 214     @Override
 215     public Set<String> supportedFileAttributeViews() {
 216         return supportedFileAttributeViews;
 217     }
 218 
 219     @Override
 220     public String toString() {
 221         return zfpath.toString();
 222     }
 223 
 224     Path getZipFile() {
 225         return zfpath;
 226     }
 227 
 228     private static final String GLOB_SYNTAX = "glob";
 229     private static final String REGEX_SYNTAX = "regex";
 230 
 231     @Override
 232     public PathMatcher getPathMatcher(String syntaxAndInput) {
 233         int pos = syntaxAndInput.indexOf(':');
 234         if (pos <= 0 || pos == syntaxAndInput.length()) {
 235             throw new IllegalArgumentException();
 236         }
 237         String syntax = syntaxAndInput.substring(0, pos);
 238         String input = syntaxAndInput.substring(pos + 1);
 239         String expr;
 240         if (syntax.equalsIgnoreCase(GLOB_SYNTAX)) {
 241             expr = toRegexPattern(input);
 242         } else {
 243             if (syntax.equalsIgnoreCase(REGEX_SYNTAX)) {
 244                 expr = input;
 245             } else {
 246                 throw new UnsupportedOperationException("Syntax '" + syntax +
 247                     "' not recognized");
 248             }
 249         }
 250         // return matcher
 251         final Pattern pattern = Pattern.compile(expr);
 252         return new PathMatcher() {
 253             @Override
 254             public boolean matches(Path path) {
 255                 return pattern.matcher(path.toString()).matches();
 256             }
 257         };
 258     }
 259 
 260     @Override
 261     public void close() throws IOException {
 262         beginWrite();
 263         try {
 264             if (!isOpen)
 265                 return;
 266             isOpen = false;          // set closed
 267         } finally {
 268             endWrite();
 269         }
 270         if (!streams.isEmpty()) {    // unlock and close all remaining streams
 271             Set<InputStream> copy = new HashSet<>(streams);
 272             for (InputStream is: copy)
 273                 is.close();
 274         }
 275         beginWrite();                // lock and sync
 276         try {
 277             AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
 278                 sync(); return null;
 279             });
 280             ch.close();              // close the ch just in case no update
 281                                      // and sync didn't close the ch
 282         } catch (PrivilegedActionException e) {
 283             throw (IOException)e.getException();
 284         } finally {
 285             endWrite();
 286         }
 287 
 288         synchronized (inflaters) {
 289             for (Inflater inf : inflaters)
 290                 inf.end();
 291         }
 292         synchronized (deflaters) {
 293             for (Deflater def : deflaters)
 294                 def.end();
 295         }
 296 
 297         IOException ioe = null;
 298         synchronized (tmppaths) {
 299             for (Path p: tmppaths) {
 300                 try {
 301                     AccessController.doPrivileged(
 302                         (PrivilegedExceptionAction<Boolean>)() -> Files.deleteIfExists(p));
 303                 } catch (PrivilegedActionException e) {
 304                     IOException x = (IOException)e.getException();
 305                     if (ioe == null)
 306                         ioe = x;
 307                     else
 308                         ioe.addSuppressed(x);
 309                 }
 310             }
 311         }
 312         provider.removeFileSystem(zfpath, this);
 313         if (ioe != null)
 314            throw ioe;
 315     }
 316 
 317     ZipFileAttributes getFileAttributes(byte[] path)
 318         throws IOException
 319     {
 320         Entry e;
 321         beginRead();
 322         try {
 323             ensureOpen();
 324             e = getEntry(path);
 325             if (e == null) {
 326                 IndexNode inode = getInode(path);
 327                 if (inode == null)
 328                     return null;
 329                 // pseudo directory, uses METHOD_STORED
 330                 e = new Entry(inode.name, inode.isdir, METHOD_STORED);
 331                 e.mtime = e.atime = e.ctime = zfsDefaultTimeStamp;
 332             }
 333         } finally {
 334             endRead();
 335         }
 336         return e;
 337     }
 338 
 339     void checkAccess(byte[] path) throws IOException {
 340         beginRead();
 341         try {
 342             ensureOpen();
 343             // is it necessary to readCEN as a sanity check?
 344             if (getInode(path) == null) {
 345                 throw new NoSuchFileException(toString());
 346             }
 347 
 348         } finally {
 349             endRead();
 350         }
 351     }
 352 
 353     void setTimes(byte[] path, FileTime mtime, FileTime atime, FileTime ctime)
 354         throws IOException
 355     {
 356         checkWritable();
 357         beginWrite();
 358         try {
 359             ensureOpen();
 360             Entry e = getEntry(path);    // ensureOpen checked
 361             if (e == null)
 362                 throw new NoSuchFileException(getString(path));
 363             if (e.type == Entry.CEN)
 364                 e.type = Entry.COPY;      // copy e
 365             if (mtime != null)
 366                 e.mtime = mtime.toMillis();
 367             if (atime != null)
 368                 e.atime = atime.toMillis();
 369             if (ctime != null)
 370                 e.ctime = ctime.toMillis();
 371             update(e);
 372         } finally {
 373             endWrite();
 374         }
 375     }
 376 
 377     boolean exists(byte[] path)
 378         throws IOException
 379     {
 380         beginRead();
 381         try {
 382             ensureOpen();
 383             return getInode(path) != null;
 384         } finally {
 385             endRead();
 386         }
 387     }
 388 
 389     boolean isDirectory(byte[] path)
 390         throws IOException
 391     {
 392         beginRead();
 393         try {
 394             IndexNode n = getInode(path);
 395             return n != null && n.isDir();
 396         } finally {
 397             endRead();
 398         }
 399     }
 400 
 401     // returns the list of child paths of "path"
 402     Iterator<Path> iteratorOf(byte[] path,
 403                               DirectoryStream.Filter<? super Path> filter)
 404         throws IOException
 405     {
 406         beginWrite();    // iteration of inodes needs exclusive lock
 407         try {
 408             ensureOpen();
 409             IndexNode inode = getInode(path);
 410             if (inode == null)
 411                 throw new NotDirectoryException(getString(path));
 412             List<Path> list = new ArrayList<>();
 413             IndexNode child = inode.child;
 414             while (child != null) {
 415                 // assume all path from zip file itself is "normalized"
 416                 ZipPath zp = new ZipPath(this, child.name, true);
 417                 if (filter == null || filter.accept(zp))
 418                     list.add(zp);
 419                 child = child.sibling;
 420             }
 421             return list.iterator();
 422         } finally {
 423             endWrite();
 424         }
 425     }
 426 
 427     void createDirectory(byte[] dir, FileAttribute<?>... attrs)
 428         throws IOException
 429     {
 430         checkWritable();
 431         //  dir = toDirectoryPath(dir);
 432         beginWrite();
 433         try {
 434             ensureOpen();
 435             if (dir.length == 0 || exists(dir))  // root dir, or exiting dir
 436                 throw new FileAlreadyExistsException(getString(dir));
 437             checkParents(dir);
 438             Entry e = new Entry(dir, Entry.NEW, true, METHOD_STORED);
 439             update(e);
 440         } finally {
 441             endWrite();
 442         }
 443     }
 444 
 445     void copyFile(boolean deletesrc, byte[]src, byte[] dst, CopyOption... options)
 446         throws IOException
 447     {
 448         checkWritable();
 449         if (Arrays.equals(src, dst))
 450             return;    // do nothing, src and dst are the same
 451 
 452         beginWrite();
 453         try {
 454             ensureOpen();
 455             Entry eSrc = getEntry(src);  // ensureOpen checked
 456 
 457             if (eSrc == null)
 458                 throw new NoSuchFileException(getString(src));
 459             if (eSrc.isDir()) {    // spec says to create dst dir
 460                 createDirectory(dst);
 461                 return;
 462             }
 463             boolean hasReplace = false;
 464             boolean hasCopyAttrs = false;
 465             for (CopyOption opt : options) {
 466                 if (opt == REPLACE_EXISTING)
 467                     hasReplace = true;
 468                 else if (opt == COPY_ATTRIBUTES)
 469                     hasCopyAttrs = true;
 470             }
 471             Entry eDst = getEntry(dst);
 472             if (eDst != null) {
 473                 if (!hasReplace)
 474                     throw new FileAlreadyExistsException(getString(dst));
 475             } else {
 476                 checkParents(dst);
 477             }
 478             Entry u = new Entry(eSrc, Entry.COPY);  // copy eSrc entry
 479             u.name(dst);                            // change name
 480             if (eSrc.type == Entry.NEW || eSrc.type == Entry.FILECH)
 481             {
 482                 u.type = eSrc.type;    // make it the same type
 483                 if (deletesrc) {       // if it's a "rename", take the data
 484                     u.bytes = eSrc.bytes;
 485                     u.file = eSrc.file;
 486                 } else {               // if it's not "rename", copy the data
 487                     if (eSrc.bytes != null)
 488                         u.bytes = Arrays.copyOf(eSrc.bytes, eSrc.bytes.length);
 489                     else if (eSrc.file != null) {
 490                         u.file = getTempPathForEntry(null);
 491                         Files.copy(eSrc.file, u.file, REPLACE_EXISTING);
 492                     }
 493                 }
 494             }
 495             if (!hasCopyAttrs)
 496                 u.mtime = u.atime= u.ctime = System.currentTimeMillis();
 497             update(u);
 498             if (deletesrc)
 499                 updateDelete(eSrc);
 500         } finally {
 501             endWrite();
 502         }
 503     }
 504 
 505     // Returns an output stream for writing the contents into the specified
 506     // entry.
 507     OutputStream newOutputStream(byte[] path, OpenOption... options)
 508         throws IOException
 509     {
 510         checkWritable();
 511         boolean hasCreateNew = false;
 512         boolean hasCreate = false;
 513         boolean hasAppend = false;
 514         boolean hasTruncate = false;
 515         for (OpenOption opt: options) {
 516             if (opt == READ)
 517                 throw new IllegalArgumentException("READ not allowed");
 518             if (opt == CREATE_NEW)
 519                 hasCreateNew = true;
 520             if (opt == CREATE)
 521                 hasCreate = true;
 522             if (opt == APPEND)
 523                 hasAppend = true;
 524             if (opt == TRUNCATE_EXISTING)
 525                 hasTruncate = true;
 526         }
 527         if (hasAppend && hasTruncate)
 528             throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
 529         beginRead();                 // only need a readlock, the "update()" will
 530         try {                        // try to obtain a writelock when the os is
 531             ensureOpen();            // being closed.
 532             Entry e = getEntry(path);
 533             if (e != null) {
 534                 if (e.isDir() || hasCreateNew)
 535                     throw new FileAlreadyExistsException(getString(path));
 536                 if (hasAppend) {
 537                     InputStream is = getInputStream(e);
 538                     OutputStream os = getOutputStream(new Entry(e, Entry.NEW));
 539                     is.transferTo(os);
 540                     is.close();
 541                     return os;
 542                 }
 543                 return getOutputStream(new Entry(e, Entry.NEW));
 544             } else {
 545                 if (!hasCreate && !hasCreateNew)
 546                     throw new NoSuchFileException(getString(path));
 547                 checkParents(path);
 548                 return getOutputStream(new Entry(path, Entry.NEW, false, defaultMethod));
 549             }
 550         } finally {
 551             endRead();
 552         }
 553     }
 554 
 555     // Returns an input stream for reading the contents of the specified
 556     // file entry.
 557     InputStream newInputStream(byte[] path) throws IOException {
 558         beginRead();
 559         try {
 560             ensureOpen();
 561             Entry e = getEntry(path);
 562             if (e == null)
 563                 throw new NoSuchFileException(getString(path));
 564             if (e.isDir())
 565                 throw new FileSystemException(getString(path), "is a directory", null);
 566             return getInputStream(e);
 567         } finally {
 568             endRead();
 569         }
 570     }
 571 
 572     private void checkOptions(Set<? extends OpenOption> options) {
 573         // check for options of null type and option is an intance of StandardOpenOption
 574         for (OpenOption option : options) {
 575             if (option == null)
 576                 throw new NullPointerException();
 577             if (!(option instanceof StandardOpenOption))
 578                 throw new IllegalArgumentException();
 579         }
 580         if (options.contains(APPEND) && options.contains(TRUNCATE_EXISTING))
 581             throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
 582     }
 583 
 584 
 585     // Returns an output SeekableByteChannel for either
 586     // (1) writing the contents of a new entry, if the entry doesn't exit, or
 587     // (2) updating/replacing the contents of an existing entry.
 588     // Note: The content is not compressed.
 589     private class EntryOutputChannel extends ByteArrayChannel {
 590         Entry e;
 591 
 592         EntryOutputChannel(Entry e) throws IOException {
 593             super(e.size > 0? (int)e.size : 8192, false);
 594             this.e = e;
 595             if (e.mtime == -1)
 596                 e.mtime = System.currentTimeMillis();
 597             if (e.method == -1)
 598                 e.method = defaultMethod;
 599             // store size, compressed size, and crc-32 in datadescriptor
 600             e.flag = FLAG_DATADESCR;
 601             if (zc.isUTF8())
 602                 e.flag |= FLAG_USE_UTF8;
 603         }
 604 
 605         @Override
 606         public void close() throws IOException {
 607             e.bytes = toByteArray();
 608             e.size = e.bytes.length;
 609             e.crc = -1;
 610             super.close();
 611             update(e);
 612         }
 613     }
 614 
 615     // Returns a Writable/ReadByteChannel for now. Might consdier to use
 616     // newFileChannel() instead, which dump the entry data into a regular
 617     // file on the default file system and create a FileChannel on top of
 618     // it.
 619     SeekableByteChannel newByteChannel(byte[] path,
 620                                        Set<? extends OpenOption> options,
 621                                        FileAttribute<?>... attrs)
 622         throws IOException
 623     {
 624         checkOptions(options);
 625         if (options.contains(StandardOpenOption.WRITE) ||
 626             options.contains(StandardOpenOption.APPEND)) {
 627             checkWritable();
 628             beginRead();    // only need a readlock, the "update()" will obtain
 629                             // thewritelock when the channel is closed
 630             try {
 631                 ensureOpen();
 632                 Entry e = getEntry(path);
 633                 if (e != null) {
 634                     if (e.isDir() || options.contains(CREATE_NEW))
 635                         throw new FileAlreadyExistsException(getString(path));
 636                     SeekableByteChannel sbc =
 637                             new EntryOutputChannel(new Entry(e, Entry.NEW));
 638                     if (options.contains(APPEND)) {
 639                         try (InputStream is = getInputStream(e)) {  // copyover
 640                             byte[] buf = new byte[8192];
 641                             ByteBuffer bb = ByteBuffer.wrap(buf);
 642                             int n;
 643                             while ((n = is.read(buf)) != -1) {
 644                                 bb.position(0);
 645                                 bb.limit(n);
 646                                 sbc.write(bb);
 647                             }
 648                         }
 649                     }
 650                     return sbc;
 651                 }
 652                 if (!options.contains(CREATE) && !options.contains(CREATE_NEW))
 653                     throw new NoSuchFileException(getString(path));
 654                 checkParents(path);
 655                 return new EntryOutputChannel(
 656                     new Entry(path, Entry.NEW, false, defaultMethod));
 657 
 658             } finally {
 659                 endRead();
 660             }
 661         } else {
 662             beginRead();
 663             try {
 664                 ensureOpen();
 665                 Entry e = getEntry(path);
 666                 if (e == null || e.isDir())
 667                     throw new NoSuchFileException(getString(path));
 668                 try (InputStream is = getInputStream(e)) {
 669                     // TBD: if (e.size < NNNNN);
 670                     return new ByteArrayChannel(is.readAllBytes(), true);
 671                 }
 672             } finally {
 673                 endRead();
 674             }
 675         }
 676     }
 677 
 678     // Returns a FileChannel of the specified entry.
 679     //
 680     // This implementation creates a temporary file on the default file system,
 681     // copy the entry data into it if the entry exists, and then create a
 682     // FileChannel on top of it.
 683     FileChannel newFileChannel(byte[] path,
 684                                Set<? extends OpenOption> options,
 685                                FileAttribute<?>... attrs)
 686         throws IOException
 687     {
 688         checkOptions(options);
 689         final  boolean forWrite = (options.contains(StandardOpenOption.WRITE) ||
 690                                    options.contains(StandardOpenOption.APPEND));
 691         beginRead();
 692         try {
 693             ensureOpen();
 694             Entry e = getEntry(path);
 695             if (forWrite) {
 696                 checkWritable();
 697                 if (e == null) {
 698                     if (!options.contains(StandardOpenOption.CREATE) &&
 699                         !options.contains(StandardOpenOption.CREATE_NEW)) {
 700                         throw new NoSuchFileException(getString(path));
 701                     }
 702                 } else {
 703                     if (options.contains(StandardOpenOption.CREATE_NEW)) {
 704                         throw new FileAlreadyExistsException(getString(path));
 705                     }
 706                     if (e.isDir())
 707                         throw new FileAlreadyExistsException("directory <"
 708                             + getString(path) + "> exists");
 709                 }
 710                 options = new HashSet<>(options);
 711                 options.remove(StandardOpenOption.CREATE_NEW); // for tmpfile
 712             } else if (e == null || e.isDir()) {
 713                 throw new NoSuchFileException(getString(path));
 714             }
 715 
 716             final boolean isFCH = (e != null && e.type == Entry.FILECH);
 717             final Path tmpfile = isFCH ? e.file : getTempPathForEntry(path);
 718             final FileChannel fch = tmpfile.getFileSystem()
 719                                            .provider()
 720                                            .newFileChannel(tmpfile, options, attrs);
 721             final Entry u = isFCH ? e : new Entry(path, tmpfile, Entry.FILECH);
 722             if (forWrite) {
 723                 u.flag = FLAG_DATADESCR;
 724                 u.method = METHOD_DEFLATED;
 725             }
 726             // is there a better way to hook into the FileChannel's close method?
 727             return new FileChannel() {
 728                 public int write(ByteBuffer src) throws IOException {
 729                     return fch.write(src);
 730                 }
 731                 public long write(ByteBuffer[] srcs, int offset, int length)
 732                     throws IOException
 733                 {
 734                     return fch.write(srcs, offset, length);
 735                 }
 736                 public long position() throws IOException {
 737                     return fch.position();
 738                 }
 739                 public FileChannel position(long newPosition)
 740                     throws IOException
 741                 {
 742                     fch.position(newPosition);
 743                     return this;
 744                 }
 745                 public long size() throws IOException {
 746                     return fch.size();
 747                 }
 748                 public FileChannel truncate(long size)
 749                     throws IOException
 750                 {
 751                     fch.truncate(size);
 752                     return this;
 753                 }
 754                 public void force(boolean metaData)
 755                     throws IOException
 756                 {
 757                     fch.force(metaData);
 758                 }
 759                 public long transferTo(long position, long count,
 760                                        WritableByteChannel target)
 761                     throws IOException
 762                 {
 763                     return fch.transferTo(position, count, target);
 764                 }
 765                 public long transferFrom(ReadableByteChannel src,
 766                                          long position, long count)
 767                     throws IOException
 768                 {
 769                     return fch.transferFrom(src, position, count);
 770                 }
 771                 public int read(ByteBuffer dst) throws IOException {
 772                     return fch.read(dst);
 773                 }
 774                 public int read(ByteBuffer dst, long position)
 775                     throws IOException
 776                 {
 777                     return fch.read(dst, position);
 778                 }
 779                 public long read(ByteBuffer[] dsts, int offset, int length)
 780                     throws IOException
 781                 {
 782                     return fch.read(dsts, offset, length);
 783                 }
 784                 public int write(ByteBuffer src, long position)
 785                     throws IOException
 786                     {
 787                    return fch.write(src, position);
 788                 }
 789                 public MappedByteBuffer map(MapMode mode,
 790                                             long position, long size)
 791                     throws IOException
 792                 {
 793                     throw new UnsupportedOperationException();
 794                 }
 795                 public FileLock lock(long position, long size, boolean shared)
 796                     throws IOException
 797                 {
 798                     return fch.lock(position, size, shared);
 799                 }
 800                 public FileLock tryLock(long position, long size, boolean shared)
 801                     throws IOException
 802                 {
 803                     return fch.tryLock(position, size, shared);
 804                 }
 805                 protected void implCloseChannel() throws IOException {
 806                     fch.close();
 807                     if (forWrite) {
 808                         u.mtime = System.currentTimeMillis();
 809                         u.size = Files.size(u.file);
 810 
 811                         update(u);
 812                     } else {
 813                         if (!isFCH)    // if this is a new fch for reading
 814                             removeTempPathForEntry(tmpfile);
 815                     }
 816                }
 817             };
 818         } finally {
 819             endRead();
 820         }
 821     }
 822 
 823     // the outstanding input streams that need to be closed
 824     private Set<InputStream> streams =
 825         Collections.synchronizedSet(new HashSet<InputStream>());
 826 
 827     private Set<Path> tmppaths = Collections.synchronizedSet(new HashSet<Path>());
 828     private Path getTempPathForEntry(byte[] path) throws IOException {
 829         Path tmpPath = createTempFileInSameDirectoryAs(zfpath);
 830         if (path != null) {
 831             Entry e = getEntry(path);
 832             if (e != null) {
 833                 try (InputStream is = newInputStream(path)) {
 834                     Files.copy(is, tmpPath, REPLACE_EXISTING);
 835                 }
 836             }
 837         }
 838         return tmpPath;
 839     }
 840 
 841     private void removeTempPathForEntry(Path path) throws IOException {
 842         Files.delete(path);
 843         tmppaths.remove(path);
 844     }
 845 
 846     // check if all parents really exit. ZIP spec does not require
 847     // the existence of any "parent directory".
 848     private void checkParents(byte[] path) throws IOException {
 849         beginRead();
 850         try {
 851             while ((path = getParent(path)) != null &&
 852                     path != ROOTPATH) {
 853                 if (!inodes.containsKey(IndexNode.keyOf(path))) {
 854                     throw new NoSuchFileException(getString(path));
 855                 }
 856             }
 857         } finally {
 858             endRead();
 859         }
 860     }
 861 
 862     private static byte[] ROOTPATH = new byte[] { '/' };
 863     private static byte[] getParent(byte[] path) {
 864         int off = getParentOff(path);
 865         if (off <= 1)
 866             return ROOTPATH;
 867         return Arrays.copyOf(path, off);
 868     }
 869 
 870     private static int getParentOff(byte[] path) {
 871         int off = path.length - 1;
 872         if (off > 0 && path[off] == '/')  // isDirectory
 873             off--;
 874         while (off > 0 && path[off] != '/') { off--; }
 875         return off;
 876     }
 877 
 878     private final void beginWrite() {
 879         rwlock.writeLock().lock();
 880     }
 881 
 882     private final void endWrite() {
 883         rwlock.writeLock().unlock();
 884     }
 885 
 886     private final void beginRead() {
 887         rwlock.readLock().lock();
 888     }
 889 
 890     private final void endRead() {
 891         rwlock.readLock().unlock();
 892     }
 893 
 894     ///////////////////////////////////////////////////////////////////
 895 
 896     private volatile boolean isOpen = true;
 897     private final SeekableByteChannel ch; // channel to the zipfile
 898     final byte[]  cen;     // CEN & ENDHDR
 899     private END  end;
 900     private long locpos;   // position of first LOC header (usually 0)
 901 
 902     private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
 903 
 904     // name -> pos (in cen), IndexNode itself can be used as a "key"
 905     private LinkedHashMap<IndexNode, IndexNode> inodes;
 906 
 907     final byte[] getBytes(String name) {
 908         return zc.getBytes(name);
 909     }
 910 
 911     final String getString(byte[] name) {
 912         return zc.toString(name);
 913     }
 914 
 915     @SuppressWarnings("deprecation")
 916     protected void finalize() throws IOException {
 917         close();
 918     }
 919 
 920     // Reads len bytes of data from the specified offset into buf.
 921     // Returns the total number of bytes read.
 922     // Each/every byte read from here (except the cen, which is mapped).
 923     final long readFullyAt(byte[] buf, int off, long len, long pos)
 924         throws IOException
 925     {
 926         ByteBuffer bb = ByteBuffer.wrap(buf);
 927         bb.position(off);
 928         bb.limit((int)(off + len));
 929         return readFullyAt(bb, pos);
 930     }
 931 
 932     private final long readFullyAt(ByteBuffer bb, long pos)
 933         throws IOException
 934     {
 935         synchronized(ch) {
 936             return ch.position(pos).read(bb);
 937         }
 938     }
 939 
 940     // Searches for end of central directory (END) header. The contents of
 941     // the END header will be read and placed in endbuf. Returns the file
 942     // position of the END header, otherwise returns -1 if the END header
 943     // was not found or an error occurred.
 944     private END findEND() throws IOException
 945     {
 946         byte[] buf = new byte[READBLOCKSZ];
 947         long ziplen = ch.size();
 948         long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
 949         long minPos = minHDR - (buf.length - ENDHDR);
 950 
 951         for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR))
 952         {
 953             int off = 0;
 954             if (pos < 0) {
 955                 // Pretend there are some NUL bytes before start of file
 956                 off = (int)-pos;
 957                 Arrays.fill(buf, 0, off, (byte)0);
 958             }
 959             int len = buf.length - off;
 960             if (readFullyAt(buf, off, len, pos + off) != len)
 961                 zerror("zip END header not found");
 962 
 963             // Now scan the block backwards for END header signature
 964             for (int i = buf.length - ENDHDR; i >= 0; i--) {
 965                 if (buf[i+0] == (byte)'P'    &&
 966                     buf[i+1] == (byte)'K'    &&
 967                     buf[i+2] == (byte)'\005' &&
 968                     buf[i+3] == (byte)'\006' &&
 969                     (pos + i + ENDHDR + ENDCOM(buf, i) == ziplen)) {
 970                     // Found END header
 971                     buf = Arrays.copyOfRange(buf, i, i + ENDHDR);
 972                     END end = new END();
 973                     end.endsub = ENDSUB(buf);
 974                     end.centot = ENDTOT(buf);
 975                     end.cenlen = ENDSIZ(buf);
 976                     end.cenoff = ENDOFF(buf);
 977                     end.comlen = ENDCOM(buf);
 978                     end.endpos = pos + i;
 979                     // try if there is zip64 end;
 980                     byte[] loc64 = new byte[ZIP64_LOCHDR];
 981                     if (end.endpos < ZIP64_LOCHDR ||
 982                         readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
 983                         != loc64.length ||
 984                         !locator64SigAt(loc64, 0)) {
 985                         return end;
 986                     }
 987                     long end64pos = ZIP64_LOCOFF(loc64);
 988                     byte[] end64buf = new byte[ZIP64_ENDHDR];
 989                     if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
 990                         != end64buf.length ||
 991                         !end64SigAt(end64buf, 0)) {
 992                         return end;
 993                     }
 994                     // end64 found,
 995                     long cenlen64 = ZIP64_ENDSIZ(end64buf);
 996                     long cenoff64 = ZIP64_ENDOFF(end64buf);
 997                     long centot64 = ZIP64_ENDTOT(end64buf);
 998                     // double-check
 999                     if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MINVAL ||
1000                         cenoff64 != end.cenoff && end.cenoff != ZIP64_MINVAL ||
1001                         centot64 != end.centot && end.centot != ZIP64_MINVAL32) {
1002                         return end;
1003                     }
1004                     // to use the end64 values
1005                     end.cenlen = cenlen64;
1006                     end.cenoff = cenoff64;
1007                     end.centot = (int)centot64; // assume total < 2g
1008                     end.endpos = end64pos;
1009                     return end;
1010                 }
1011             }
1012         }
1013         zerror("zip END header not found");
1014         return null; //make compiler happy
1015     }
1016 
1017     // Reads zip file central directory. Returns the file position of first
1018     // CEN header, otherwise returns -1 if an error occurred. If zip->msg != NULL
1019     // then the error was a zip format error and zip->msg has the error text.
1020     // Always pass in -1 for knownTotal; it's used for a recursive call.
1021     private byte[] initCEN() throws IOException {
1022         end = findEND();
1023         if (end.endpos == 0) {
1024             inodes = new LinkedHashMap<>(10);
1025             locpos = 0;
1026             buildNodeTree();
1027             return null;         // only END header present
1028         }
1029         if (end.cenlen > end.endpos)
1030             zerror("invalid END header (bad central directory size)");
1031         long cenpos = end.endpos - end.cenlen;     // position of CEN table
1032 
1033         // Get position of first local file (LOC) header, taking into
1034         // account that there may be a stub prefixed to the zip file.
1035         locpos = cenpos - end.cenoff;
1036         if (locpos < 0)
1037             zerror("invalid END header (bad central directory offset)");
1038 
1039         // read in the CEN and END
1040         byte[] cen = new byte[(int)(end.cenlen + ENDHDR)];
1041         if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
1042             zerror("read CEN tables failed");
1043         }
1044         // Iterate through the entries in the central directory
1045         inodes = new LinkedHashMap<>(end.centot + 1);
1046         int pos = 0;
1047         int limit = cen.length - ENDHDR;
1048         while (pos < limit) {
1049             if (!cenSigAt(cen, pos))
1050                 zerror("invalid CEN header (bad signature)");
1051             int method = CENHOW(cen, pos);
1052             int nlen   = CENNAM(cen, pos);
1053             int elen   = CENEXT(cen, pos);
1054             int clen   = CENCOM(cen, pos);
1055             if ((CENFLG(cen, pos) & 1) != 0) {
1056                 zerror("invalid CEN header (encrypted entry)");
1057             }
1058             if (method != METHOD_STORED && method != METHOD_DEFLATED) {
1059                 zerror("invalid CEN header (unsupported compression method: " + method + ")");
1060             }
1061             if (pos + CENHDR + nlen > limit) {
1062                 zerror("invalid CEN header (bad header size)");
1063             }
1064             IndexNode inode = new IndexNode(cen, pos + CENHDR, pos, nlen);
1065             inodes.put(inode, inode);
1066 
1067             // skip ext and comment
1068             pos += (CENHDR + nlen + elen + clen);
1069         }
1070         if (pos + ENDHDR != cen.length) {
1071             zerror("invalid CEN header (bad header size)");
1072         }
1073         buildNodeTree();
1074         return cen;
1075     }
1076 
1077     private void ensureOpen() throws IOException {
1078         if (!isOpen)
1079             throw new ClosedFileSystemException();
1080     }
1081 
1082     // Creates a new empty temporary file in the same directory as the
1083     // specified file.  A variant of Files.createTempFile.
1084     private Path createTempFileInSameDirectoryAs(Path path)
1085         throws IOException
1086     {
1087         Path parent = path.toAbsolutePath().getParent();
1088         Path dir = (parent == null) ? path.getFileSystem().getPath(".") : parent;
1089         Path tmpPath = Files.createTempFile(dir, "zipfstmp", null);
1090         tmppaths.add(tmpPath);
1091         return tmpPath;
1092     }
1093 
1094     ////////////////////update & sync //////////////////////////////////////
1095 
1096     private boolean hasUpdate = false;
1097 
1098     // shared key. consumer guarantees the "writeLock" before use it.
1099     private final IndexNode LOOKUPKEY = new IndexNode(null, -1);
1100 
1101     private void updateDelete(IndexNode inode) {
1102         beginWrite();
1103         try {
1104             removeFromTree(inode);
1105             inodes.remove(inode);
1106             hasUpdate = true;
1107         } finally {
1108              endWrite();
1109         }
1110     }
1111 
1112     private void update(Entry e) {
1113         beginWrite();
1114         try {
1115             IndexNode old = inodes.put(e, e);
1116             if (old != null) {
1117                 removeFromTree(old);
1118             }
1119             if (e.type == Entry.NEW || e.type == Entry.FILECH || e.type == Entry.COPY) {
1120                 IndexNode parent = inodes.get(LOOKUPKEY.as(getParent(e.name)));
1121                 e.sibling = parent.child;
1122                 parent.child = e;
1123             }
1124             hasUpdate = true;
1125         } finally {
1126             endWrite();
1127         }
1128     }
1129 
1130     // copy over the whole LOC entry (header if necessary, data and ext) from
1131     // old zip to the new one.
1132     private long copyLOCEntry(Entry e, boolean updateHeader,
1133                               OutputStream os,
1134                               long written, byte[] buf)
1135         throws IOException
1136     {
1137         long locoff = e.locoff;  // where to read
1138         e.locoff = written;      // update the e.locoff with new value
1139 
1140         // calculate the size need to write out
1141         long size = 0;
1142         //  if there is A ext
1143         if ((e.flag & FLAG_DATADESCR) != 0) {
1144             if (e.size >= ZIP64_MINVAL || e.csize >= ZIP64_MINVAL)
1145                 size = 24;
1146             else
1147                 size = 16;
1148         }
1149         // read loc, use the original loc.elen/nlen
1150         if (readFullyAt(buf, 0, LOCHDR , locoff) != LOCHDR)
1151             throw new ZipException("loc: reading failed");
1152         if (updateHeader) {
1153             locoff += LOCHDR + LOCNAM(buf) + LOCEXT(buf);  // skip header
1154             size += e.csize;
1155             written = e.writeLOC(os) + size;
1156         } else {
1157             os.write(buf, 0, LOCHDR);    // write out the loc header
1158             locoff += LOCHDR;
1159             // use e.csize,  LOCSIZ(buf) is zero if FLAG_DATADESCR is on
1160             // size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf);
1161             size += LOCNAM(buf) + LOCEXT(buf) + e.csize;
1162             written = LOCHDR + size;
1163         }
1164         int n;
1165         while (size > 0 &&
1166             (n = (int)readFullyAt(buf, 0, buf.length, locoff)) != -1)
1167         {
1168             if (size < n)
1169                 n = (int)size;
1170             os.write(buf, 0, n);
1171             size -= n;
1172             locoff += n;
1173         }
1174         return written;
1175     }
1176 
1177     private long writeEntry(Entry e, OutputStream os, byte[] buf)
1178         throws IOException {
1179 
1180         if (e.bytes == null && e.file == null)    // dir, 0-length data
1181             return 0;
1182 
1183         long written = 0;
1184         try (OutputStream os2 = e.method == METHOD_STORED ?
1185             new EntryOutputStreamCRC32(e, os) : new EntryOutputStreamDef(e, os)) {
1186             if (e.bytes != null) {                 // in-memory
1187                 os2.write(e.bytes, 0, e.bytes.length);
1188             } else if (e.file != null) {           // tmp file
1189                 if (e.type == Entry.NEW || e.type == Entry.FILECH) {
1190                     try (InputStream is = Files.newInputStream(e.file)) {
1191                         is.transferTo(os2);
1192                     }
1193                 }
1194                 Files.delete(e.file);
1195                 tmppaths.remove(e.file);
1196             }
1197         }
1198         written += e.csize;
1199         if ((e.flag & FLAG_DATADESCR) != 0) {
1200             written += e.writeEXT(os);
1201         }
1202         return written;
1203     }
1204 
1205     // sync the zip file system, if there is any udpate
1206     private void sync() throws IOException {
1207 
1208         if (!hasUpdate)
1209             return;
1210         Path tmpFile = createTempFileInSameDirectoryAs(zfpath);
1211         try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(tmpFile, WRITE)))
1212         {
1213             ArrayList<Entry> elist = new ArrayList<>(inodes.size());
1214             long written = 0;
1215             byte[] buf = new byte[8192];
1216             Entry e = null;
1217 
1218             // write loc
1219             for (IndexNode inode : inodes.values()) {
1220                 if (inode instanceof Entry) {    // an updated inode
1221                     e = (Entry)inode;
1222                     try {
1223                         if (e.type == Entry.COPY) {
1224                             // entry copy: the only thing changed is the "name"
1225                             // and "nlen" in LOC header, so we udpate/rewrite the
1226                             // LOC in new file and simply copy the rest (data and
1227                             // ext) without enflating/deflating from the old zip
1228                             // file LOC entry.
1229                             written += copyLOCEntry(e, true, os, written, buf);
1230                         } else {                          // NEW, FILECH or CEN
1231                             e.locoff = written;
1232                             written += e.writeLOC(os);    // write loc header
1233                             written += writeEntry(e, os, buf);
1234                         }
1235                         elist.add(e);
1236                     } catch (IOException x) {
1237                         x.printStackTrace();    // skip any in-accurate entry
1238                     }
1239                 } else {                        // unchanged inode
1240                     if (inode.pos == -1) {
1241                         continue;               // pseudo directory node
1242                     }
1243                     e = Entry.readCEN(this, inode);
1244                     try {
1245                         written += copyLOCEntry(e, false, os, written, buf);
1246                         elist.add(e);
1247                     } catch (IOException x) {
1248                         x.printStackTrace();    // skip any wrong entry
1249                     }
1250                 }
1251             }
1252 
1253             // now write back the cen and end table
1254             end.cenoff = written;
1255             for (Entry entry : elist) {
1256                 written += entry.writeCEN(os);
1257             }
1258             end.centot = elist.size();
1259             end.cenlen = written - end.cenoff;
1260             end.write(os, written, forceEnd64);
1261         }
1262 
1263         ch.close();
1264         Files.delete(zfpath);
1265         Files.move(tmpFile, zfpath, REPLACE_EXISTING);
1266         hasUpdate = false;    // clear
1267     }
1268 
1269     IndexNode getInode(byte[] path) {
1270         if (path == null)
1271             throw new NullPointerException("path");
1272         return inodes.get(IndexNode.keyOf(path));
1273     }
1274 
1275     Entry getEntry(byte[] path) throws IOException {
1276         IndexNode inode = getInode(path);
1277         if (inode instanceof Entry)
1278             return (Entry)inode;
1279         if (inode == null || inode.pos == -1)
1280             return null;
1281         return Entry.readCEN(this, inode);
1282     }
1283 
1284     public void deleteFile(byte[] path, boolean failIfNotExists)
1285         throws IOException
1286     {
1287         checkWritable();
1288 
1289         IndexNode inode = getInode(path);
1290         if (inode == null) {
1291             if (path != null && path.length == 0)
1292                 throw new ZipException("root directory </> can't not be delete");
1293             if (failIfNotExists)
1294                 throw new NoSuchFileException(getString(path));
1295         } else {
1296             if (inode.isDir() && inode.child != null)
1297                 throw new DirectoryNotEmptyException(getString(path));
1298             updateDelete(inode);
1299         }
1300     }
1301 
1302     // Returns an out stream for either
1303     // (1) writing the contents of a new entry, if the entry exits, or
1304     // (2) updating/replacing the contents of the specified existing entry.
1305     private OutputStream getOutputStream(Entry e) throws IOException {
1306 
1307         if (e.mtime == -1)
1308             e.mtime = System.currentTimeMillis();
1309         if (e.method == -1)
1310             e.method = defaultMethod;
1311         // store size, compressed size, and crc-32 in datadescr
1312         e.flag = FLAG_DATADESCR;
1313         if (zc.isUTF8())
1314             e.flag |= FLAG_USE_UTF8;
1315         OutputStream os;
1316         if (useTempFile) {
1317             e.file = getTempPathForEntry(null);
1318             os = Files.newOutputStream(e.file, WRITE);
1319         } else {
1320             os = new ByteArrayOutputStream((e.size > 0)? (int)e.size : 8192);
1321         }
1322         return new EntryOutputStream(e, os);
1323     }
1324 
1325     private class EntryOutputStream extends FilterOutputStream {
1326         private Entry e;
1327         private long written;
1328         private boolean isClosed;
1329 
1330         EntryOutputStream(Entry e, OutputStream os) throws IOException {
1331             super(os);
1332             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1333             // this.written = 0;
1334         }
1335 
1336         @Override
1337         public synchronized void write(int b) throws IOException {
1338             out.write(b);
1339             written += 1;
1340         }
1341 
1342         @Override
1343         public synchronized void write(byte b[], int off, int len)
1344                 throws IOException {
1345             out.write(b, off, len);
1346             written += len;
1347         }
1348 
1349         @Override
1350         public synchronized void close() throws IOException {
1351             if (isClosed) {
1352                 return;
1353             }
1354             isClosed = true;
1355             e.size = written;
1356             if (out instanceof ByteArrayOutputStream)
1357                 e.bytes = ((ByteArrayOutputStream)out).toByteArray();
1358             super.close();
1359             update(e);
1360         }
1361     }
1362 
1363     // Wrapper output stream class to write out a "stored" entry.
1364     // (1) this class does not close the underlying out stream when
1365     //     being closed.
1366     // (2) no need to be "synchronized", only used by sync()
1367     private class EntryOutputStreamCRC32 extends FilterOutputStream {
1368         private Entry e;
1369         private CRC32 crc;
1370         private long written;
1371         private boolean isClosed;
1372 
1373         EntryOutputStreamCRC32(Entry e, OutputStream os) throws IOException {
1374             super(os);
1375             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1376             this.crc = new CRC32();
1377         }
1378 
1379         @Override
1380         public void write(int b) throws IOException {
1381             out.write(b);
1382             crc.update(b);
1383             written += 1;
1384         }
1385 
1386         @Override
1387         public void write(byte b[], int off, int len)
1388                 throws IOException {
1389             out.write(b, off, len);
1390             crc.update(b, off, len);
1391             written += len;
1392         }
1393 
1394         @Override
1395         public void close() throws IOException {
1396             if (isClosed)
1397                 return;
1398             isClosed = true;
1399             e.size = e.csize = written;
1400             e.size = crc.getValue();
1401         }
1402     }
1403 
1404     // Wrapper output stream class to write out a "deflated" entry.
1405     // (1) this class does not close the underlying out stream when
1406     //     being closed.
1407     // (2) no need to be "synchronized", only used by sync()
1408     private class EntryOutputStreamDef extends DeflaterOutputStream {
1409         private CRC32 crc;
1410         private Entry e;
1411         private boolean isClosed;
1412 
1413         EntryOutputStreamDef(Entry e, OutputStream os) throws IOException {
1414             super(os, getDeflater());
1415             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1416             this.crc = new CRC32();
1417         }
1418 
1419         @Override
1420         public void write(byte b[], int off, int len)
1421                 throws IOException {
1422             super.write(b, off, len);
1423             crc.update(b, off, len);
1424         }
1425 
1426         @Override
1427         public void close() throws IOException {
1428             if (isClosed)
1429                 return;
1430             isClosed = true;
1431             finish();
1432             e.size  = def.getBytesRead();
1433             e.csize = def.getBytesWritten();
1434             e.crc = crc.getValue();
1435         }
1436     }
1437 
1438     private InputStream getInputStream(Entry e)
1439         throws IOException
1440     {
1441         InputStream eis = null;
1442 
1443         if (e.type == Entry.NEW) {
1444             // now bytes & file is uncompressed.
1445             if (e.bytes != null)
1446                 return new ByteArrayInputStream(e.bytes);
1447             else if (e.file != null)
1448                 return Files.newInputStream(e.file);
1449             else
1450                 throw new ZipException("update entry data is missing");
1451         } else if (e.type == Entry.FILECH) {
1452             // FILECH result is un-compressed.
1453             eis = Files.newInputStream(e.file);
1454             // TBD: wrap to hook close()
1455             // streams.add(eis);
1456             return eis;
1457         } else {  // untouced  CEN or COPY
1458             eis = new EntryInputStream(e, ch);
1459         }
1460         if (e.method == METHOD_DEFLATED) {
1461             // MORE: Compute good size for inflater stream:
1462             long bufSize = e.size + 2; // Inflater likes a bit of slack
1463             if (bufSize > 65536)
1464                 bufSize = 8192;
1465             final long size = e.size;
1466             eis = new InflaterInputStream(eis, getInflater(), (int)bufSize) {
1467                 private boolean isClosed = false;
1468                 public void close() throws IOException {
1469                     if (!isClosed) {
1470                         releaseInflater(inf);
1471                         this.in.close();
1472                         isClosed = true;
1473                         streams.remove(this);
1474                     }
1475                 }
1476                 // Override fill() method to provide an extra "dummy" byte
1477                 // at the end of the input stream. This is required when
1478                 // using the "nowrap" Inflater option. (it appears the new
1479                 // zlib in 7 does not need it, but keep it for now)
1480                 protected void fill() throws IOException {
1481                     if (eof) {
1482                         throw new EOFException(
1483                             "Unexpected end of ZLIB input stream");
1484                     }
1485                     len = this.in.read(buf, 0, buf.length);
1486                     if (len == -1) {
1487                         buf[0] = 0;
1488                         len = 1;
1489                         eof = true;
1490                     }
1491                     inf.setInput(buf, 0, len);
1492                 }
1493                 private boolean eof;
1494 
1495                 public int available() throws IOException {
1496                     if (isClosed)
1497                         return 0;
1498                     long avail = size - inf.getBytesWritten();
1499                     return avail > (long) Integer.MAX_VALUE ?
1500                         Integer.MAX_VALUE : (int) avail;
1501                 }
1502             };
1503         } else if (e.method == METHOD_STORED) {
1504             // TBD: wrap/ it does not seem necessary
1505         } else {
1506             throw new ZipException("invalid compression method");
1507         }
1508         streams.add(eis);
1509         return eis;
1510     }
1511 
1512     // Inner class implementing the input stream used to read
1513     // a (possibly compressed) zip file entry.
1514     private class EntryInputStream extends InputStream {
1515         private final SeekableByteChannel zfch; // local ref to zipfs's "ch". zipfs.ch might
1516                                           // point to a new channel after sync()
1517         private   long pos;               // current position within entry data
1518         protected long rem;               // number of remaining bytes within entry
1519         protected final long size;        // uncompressed size of this entry
1520 
1521         EntryInputStream(Entry e, SeekableByteChannel zfch)
1522             throws IOException
1523         {
1524             this.zfch = zfch;
1525             rem = e.csize;
1526             size = e.size;
1527             pos = e.locoff;
1528             if (pos == -1) {
1529                 Entry e2 = getEntry(e.name);
1530                 if (e2 == null) {
1531                     throw new ZipException("invalid loc for entry <" + e.name + ">");
1532                 }
1533                 pos = e2.locoff;
1534             }
1535             pos = -pos;  // lazy initialize the real data offset
1536         }
1537 
1538         public int read(byte b[], int off, int len) throws IOException {
1539             ensureOpen();
1540             initDataPos();
1541             if (rem == 0) {
1542                 return -1;
1543             }
1544             if (len <= 0) {
1545                 return 0;
1546             }
1547             if (len > rem) {
1548                 len = (int) rem;
1549             }
1550             // readFullyAt()
1551             long n = 0;
1552             ByteBuffer bb = ByteBuffer.wrap(b);
1553             bb.position(off);
1554             bb.limit(off + len);
1555             synchronized(zfch) {
1556                 n = zfch.position(pos).read(bb);
1557             }
1558             if (n > 0) {
1559                 pos += n;
1560                 rem -= n;
1561             }
1562             if (rem == 0) {
1563                 close();
1564             }
1565             return (int)n;
1566         }
1567 
1568         public int read() throws IOException {
1569             byte[] b = new byte[1];
1570             if (read(b, 0, 1) == 1) {
1571                 return b[0] & 0xff;
1572             } else {
1573                 return -1;
1574             }
1575         }
1576 
1577         public long skip(long n) throws IOException {
1578             ensureOpen();
1579             if (n > rem)
1580                 n = rem;
1581             pos += n;
1582             rem -= n;
1583             if (rem == 0) {
1584                 close();
1585             }
1586             return n;
1587         }
1588 
1589         public int available() {
1590             return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
1591         }
1592 
1593         public long size() {
1594             return size;
1595         }
1596 
1597         public void close() {
1598             rem = 0;
1599             streams.remove(this);
1600         }
1601 
1602         private void initDataPos() throws IOException {
1603             if (pos <= 0) {
1604                 pos = -pos + locpos;
1605                 byte[] buf = new byte[LOCHDR];
1606                 if (readFullyAt(buf, 0, buf.length, pos) != LOCHDR) {
1607                     throw new ZipException("invalid loc " + pos + " for entry reading");
1608                 }
1609                 pos += LOCHDR + LOCNAM(buf) + LOCEXT(buf);
1610             }
1611         }
1612     }
1613 
1614     static void zerror(String msg) throws ZipException {
1615         throw new ZipException(msg);
1616     }
1617 
1618     // Maxmum number of de/inflater we cache
1619     private final int MAX_FLATER = 20;
1620     // List of available Inflater objects for decompression
1621     private final List<Inflater> inflaters = new ArrayList<>();
1622 
1623     // Gets an inflater from the list of available inflaters or allocates
1624     // a new one.
1625     private Inflater getInflater() {
1626         synchronized (inflaters) {
1627             int size = inflaters.size();
1628             if (size > 0) {
1629                 Inflater inf = inflaters.remove(size - 1);
1630                 return inf;
1631             } else {
1632                 return new Inflater(true);
1633             }
1634         }
1635     }
1636 
1637     // Releases the specified inflater to the list of available inflaters.
1638     private void releaseInflater(Inflater inf) {
1639         synchronized (inflaters) {
1640             if (inflaters.size() < MAX_FLATER) {
1641                 inf.reset();
1642                 inflaters.add(inf);
1643             } else {
1644                 inf.end();
1645             }
1646         }
1647     }
1648 
1649     // List of available Deflater objects for compression
1650     private final List<Deflater> deflaters = new ArrayList<>();
1651 
1652     // Gets an deflater from the list of available deflaters or allocates
1653     // a new one.
1654     private Deflater getDeflater() {
1655         synchronized (deflaters) {
1656             int size = deflaters.size();
1657             if (size > 0) {
1658                 Deflater def = deflaters.remove(size - 1);
1659                 return def;
1660             } else {
1661                 return new Deflater(Deflater.DEFAULT_COMPRESSION, true);
1662             }
1663         }
1664     }
1665 
1666     // Releases the specified inflater to the list of available inflaters.
1667     private void releaseDeflater(Deflater def) {
1668         synchronized (deflaters) {
1669             if (inflaters.size() < MAX_FLATER) {
1670                def.reset();
1671                deflaters.add(def);
1672             } else {
1673                def.end();
1674             }
1675         }
1676     }
1677 
1678     // End of central directory record
1679     static class END {
1680         // these 2 fields are not used by anyone and write() uses "0"
1681         // int  disknum;
1682         // int  sdisknum;
1683         int  endsub;     // endsub
1684         int  centot;     // 4 bytes
1685         long cenlen;     // 4 bytes
1686         long cenoff;     // 4 bytes
1687         int  comlen;     // comment length
1688         byte[] comment;
1689 
1690         /* members of Zip64 end of central directory locator */
1691         // int diskNum;
1692         long endpos;
1693         // int disktot;
1694 
1695         void write(OutputStream os, long offset, boolean forceEnd64) throws IOException {
1696             boolean hasZip64 = forceEnd64; // false;
1697             long xlen = cenlen;
1698             long xoff = cenoff;
1699             if (xlen >= ZIP64_MINVAL) {
1700                 xlen = ZIP64_MINVAL;
1701                 hasZip64 = true;
1702             }
1703             if (xoff >= ZIP64_MINVAL) {
1704                 xoff = ZIP64_MINVAL;
1705                 hasZip64 = true;
1706             }
1707             int count = centot;
1708             if (count >= ZIP64_MINVAL32) {
1709                 count = ZIP64_MINVAL32;
1710                 hasZip64 = true;
1711             }
1712             if (hasZip64) {
1713                 long off64 = offset;
1714                 //zip64 end of central directory record
1715                 writeInt(os, ZIP64_ENDSIG);       // zip64 END record signature
1716                 writeLong(os, ZIP64_ENDHDR - 12); // size of zip64 end
1717                 writeShort(os, 45);               // version made by
1718                 writeShort(os, 45);               // version needed to extract
1719                 writeInt(os, 0);                  // number of this disk
1720                 writeInt(os, 0);                  // central directory start disk
1721                 writeLong(os, centot);            // number of directory entries on disk
1722                 writeLong(os, centot);            // number of directory entries
1723                 writeLong(os, cenlen);            // length of central directory
1724                 writeLong(os, cenoff);            // offset of central directory
1725 
1726                 //zip64 end of central directory locator
1727                 writeInt(os, ZIP64_LOCSIG);       // zip64 END locator signature
1728                 writeInt(os, 0);                  // zip64 END start disk
1729                 writeLong(os, off64);             // offset of zip64 END
1730                 writeInt(os, 1);                  // total number of disks (?)
1731             }
1732             writeInt(os, ENDSIG);                 // END record signature
1733             writeShort(os, 0);                    // number of this disk
1734             writeShort(os, 0);                    // central directory start disk
1735             writeShort(os, count);                // number of directory entries on disk
1736             writeShort(os, count);                // total number of directory entries
1737             writeInt(os, xlen);                   // length of central directory
1738             writeInt(os, xoff);                   // offset of central directory
1739             if (comment != null) {            // zip file comment
1740                 writeShort(os, comment.length);
1741                 writeBytes(os, comment);
1742             } else {
1743                 writeShort(os, 0);
1744             }
1745         }
1746     }
1747 
1748     // Internal node that links a "name" to its pos in cen table.
1749     // The node itself can be used as a "key" to lookup itself in
1750     // the HashMap inodes.
1751     static class IndexNode {
1752         byte[] name;
1753         int    hashcode;  // node is hashable/hashed by its name
1754         int    pos = -1;  // position in cen table, -1 menas the
1755                           // entry does not exists in zip file
1756         boolean isdir;
1757 
1758         IndexNode(byte[] name, boolean isdir) {
1759             name(name);
1760             this.isdir = isdir;
1761             this.pos = -1;
1762         }
1763 
1764         IndexNode(byte[] name, int pos) {
1765             name(name);
1766             this.pos = pos;
1767         }
1768 
1769         // constructor for cenInit()
1770         IndexNode(byte[] cen, int noff, int pos, int nlen) {
1771             if (cen[noff + nlen - 1] == '/') {
1772                 isdir = true;
1773                 nlen--;
1774             }
1775             name = new byte[nlen + 1];
1776             System.arraycopy(cen, pos + CENHDR, name, 1, nlen);
1777             name[0] = '/';
1778             name(name);
1779             this.pos = pos;
1780         }
1781 
1782         private static final ThreadLocal<IndexNode> cachedKey = new ThreadLocal<>();
1783 
1784         final static IndexNode keyOf(byte[] name) { // get a lookup key;
1785             IndexNode key = cachedKey.get();
1786             if (key == null) {
1787                 key = new IndexNode(name, -1);
1788                 cachedKey.set(key);
1789             }
1790             return key.as(name);
1791         }
1792 
1793         final void name(byte[] name) {
1794             this.name = name;
1795             this.hashcode = Arrays.hashCode(name);
1796         }
1797 
1798         final IndexNode as(byte[] name) {           // reuse the node, mostly
1799             name(name);                             // as a lookup "key"
1800             return this;
1801         }
1802 
1803         boolean isDir() {
1804             return isdir;
1805         }
1806 
1807         public boolean equals(Object other) {
1808             if (!(other instanceof IndexNode)) {
1809                 return false;
1810             }
1811             if (other instanceof ParentLookup) {
1812                 return ((ParentLookup)other).equals(this);
1813             }
1814             return Arrays.equals(name, ((IndexNode)other).name);
1815         }
1816 
1817         public int hashCode() {
1818             return hashcode;
1819         }
1820 
1821         IndexNode() {}
1822         IndexNode sibling;
1823         IndexNode child;  // 1st child
1824     }
1825 
1826     static class Entry extends IndexNode implements ZipFileAttributes {
1827 
1828         static final int CEN    = 1;  // entry read from cen
1829         static final int NEW    = 2;  // updated contents in bytes or file
1830         static final int FILECH = 3;  // fch update in "file"
1831         static final int COPY   = 4;  // copy of a CEN entry
1832 
1833         byte[] bytes;                 // updated content bytes
1834         Path   file;                  // use tmp file to store bytes;
1835         int    type = CEN;            // default is the entry read from cen
1836 
1837         // entry attributes
1838         int    version;
1839         int    flag;
1840         int    method = -1;    // compression method
1841         long   mtime  = -1;    // last modification time (in DOS time)
1842         long   atime  = -1;    // last access time
1843         long   ctime  = -1;    // create time
1844         long   crc    = -1;    // crc-32 of entry data
1845         long   csize  = -1;    // compressed size of entry data
1846         long   size   = -1;    // uncompressed size of entry data
1847         byte[] extra;
1848 
1849         // cen
1850 
1851         // these fields are not used by anyone and writeCEN uses "0"
1852         // int    versionMade;
1853         // int    disk;
1854         // int    attrs;
1855         // long   attrsEx;
1856         long   locoff;
1857         byte[] comment;
1858 
1859         Entry() {}
1860 
1861         Entry(byte[] name, boolean isdir, int method) {
1862             name(name);
1863             this.isdir = isdir;
1864             this.mtime  = this.ctime = this.atime = System.currentTimeMillis();
1865             this.crc    = 0;
1866             this.size   = 0;
1867             this.csize  = 0;
1868             this.method = method;
1869         }
1870 
1871         Entry(byte[] name, int type, boolean isdir, int method) {
1872             this(name, isdir, method);
1873             this.type = type;
1874         }
1875 
1876         Entry (Entry e, int type) {
1877             name(e.name);
1878             this.isdir     = e.isdir;
1879             this.version   = e.version;
1880             this.ctime     = e.ctime;
1881             this.atime     = e.atime;
1882             this.mtime     = e.mtime;
1883             this.crc       = e.crc;
1884             this.size      = e.size;
1885             this.csize     = e.csize;
1886             this.method    = e.method;
1887             this.extra     = e.extra;
1888             /*
1889             this.versionMade = e.versionMade;
1890             this.disk      = e.disk;
1891             this.attrs     = e.attrs;
1892             this.attrsEx   = e.attrsEx;
1893             */
1894             this.locoff    = e.locoff;
1895             this.comment   = e.comment;
1896             this.type      = type;
1897         }
1898 
1899         Entry (byte[] name, Path file, int type) {
1900             this(name, type, false, METHOD_STORED);
1901             this.file = file;
1902         }
1903 
1904         int version() throws ZipException {
1905             if (method == METHOD_DEFLATED)
1906                 return 20;
1907             else if (method == METHOD_STORED)
1908                 return 10;
1909             throw new ZipException("unsupported compression method");
1910         }
1911 
1912         ///////////////////// CEN //////////////////////
1913         static Entry readCEN(ZipFileSystem zipfs, IndexNode inode)
1914             throws IOException
1915         {
1916             return new Entry().cen(zipfs, inode);
1917         }
1918 
1919         private Entry cen(ZipFileSystem zipfs, IndexNode inode)
1920             throws IOException
1921         {
1922             byte[] cen = zipfs.cen;
1923             int pos = inode.pos;
1924             if (!cenSigAt(cen, pos))
1925                 zerror("invalid CEN header (bad signature)");
1926             version     = CENVER(cen, pos);
1927             flag        = CENFLG(cen, pos);
1928             method      = CENHOW(cen, pos);
1929             mtime       = dosToJavaTime(CENTIM(cen, pos));
1930             crc         = CENCRC(cen, pos);
1931             csize       = CENSIZ(cen, pos);
1932             size        = CENLEN(cen, pos);
1933             int nlen    = CENNAM(cen, pos);
1934             int elen    = CENEXT(cen, pos);
1935             int clen    = CENCOM(cen, pos);
1936             /*
1937             versionMade = CENVEM(cen, pos);
1938             disk        = CENDSK(cen, pos);
1939             attrs       = CENATT(cen, pos);
1940             attrsEx     = CENATX(cen, pos);
1941             */
1942             locoff      = CENOFF(cen, pos);
1943             pos += CENHDR;
1944             this.name = inode.name;
1945             this.isdir = inode.isdir;
1946             this.hashcode = inode.hashcode;
1947 
1948             pos += nlen;
1949             if (elen > 0) {
1950                 extra = Arrays.copyOfRange(cen, pos, pos + elen);
1951                 pos += elen;
1952                 readExtra(zipfs);
1953             }
1954             if (clen > 0) {
1955                 comment = Arrays.copyOfRange(cen, pos, pos + clen);
1956             }
1957             return this;
1958         }
1959 
1960         int writeCEN(OutputStream os) throws IOException
1961         {
1962             int written  = CENHDR;
1963             int version0 = version();
1964             long csize0  = csize;
1965             long size0   = size;
1966             long locoff0 = locoff;
1967             int elen64   = 0;                // extra for ZIP64
1968             int elenNTFS = 0;                // extra for NTFS (a/c/mtime)
1969             int elenEXTT = 0;                // extra for Extended Timestamp
1970             boolean foundExtraTime = false;  // if time stamp NTFS, EXTT present
1971 
1972             byte[] zname = isdir ? toDirectoryPath(name) : name;
1973 
1974             // confirm size/length
1975             int nlen = (zname != null) ? zname.length - 1 : 0;  // name has [0] as "slash"
1976             int elen = (extra != null) ? extra.length : 0;
1977             int eoff = 0;
1978             int clen = (comment != null) ? comment.length : 0;
1979             if (csize >= ZIP64_MINVAL) {
1980                 csize0 = ZIP64_MINVAL;
1981                 elen64 += 8;                 // csize(8)
1982             }
1983             if (size >= ZIP64_MINVAL) {
1984                 size0 = ZIP64_MINVAL;        // size(8)
1985                 elen64 += 8;
1986             }
1987             if (locoff >= ZIP64_MINVAL) {
1988                 locoff0 = ZIP64_MINVAL;
1989                 elen64 += 8;                 // offset(8)
1990             }
1991             if (elen64 != 0) {
1992                 elen64 += 4;                 // header and data sz 4 bytes
1993             }
1994             while (eoff + 4 < elen) {
1995                 int tag = SH(extra, eoff);
1996                 int sz = SH(extra, eoff + 2);
1997                 if (tag == EXTID_EXTT || tag == EXTID_NTFS) {
1998                     foundExtraTime = true;
1999                 }
2000                 eoff += (4 + sz);
2001             }
2002             if (!foundExtraTime) {
2003                 if (isWindows) {             // use NTFS
2004                     elenNTFS = 36;           // total 36 bytes
2005                 } else {                     // Extended Timestamp otherwise
2006                     elenEXTT = 9;            // only mtime in cen
2007                 }
2008             }
2009             writeInt(os, CENSIG);            // CEN header signature
2010             if (elen64 != 0) {
2011                 writeShort(os, 45);          // ver 4.5 for zip64
2012                 writeShort(os, 45);
2013             } else {
2014                 writeShort(os, version0);    // version made by
2015                 writeShort(os, version0);    // version needed to extract
2016             }
2017             writeShort(os, flag);            // general purpose bit flag
2018             writeShort(os, method);          // compression method
2019                                              // last modification time
2020             writeInt(os, (int)javaToDosTime(mtime));
2021             writeInt(os, crc);               // crc-32
2022             writeInt(os, csize0);            // compressed size
2023             writeInt(os, size0);             // uncompressed size
2024             writeShort(os, nlen);
2025             writeShort(os, elen + elen64 + elenNTFS + elenEXTT);
2026 
2027             if (comment != null) {
2028                 writeShort(os, Math.min(clen, 0xffff));
2029             } else {
2030                 writeShort(os, 0);
2031             }
2032             writeShort(os, 0);              // starting disk number
2033             writeShort(os, 0);              // internal file attributes (unused)
2034             writeInt(os, 0);                // external file attributes (unused)
2035             writeInt(os, locoff0);          // relative offset of local header
2036             writeBytes(os, zname, 1, nlen);
2037             if (elen64 != 0) {
2038                 writeShort(os, EXTID_ZIP64);// Zip64 extra
2039                 writeShort(os, elen64 - 4); // size of "this" extra block
2040                 if (size0 == ZIP64_MINVAL)
2041                     writeLong(os, size);
2042                 if (csize0 == ZIP64_MINVAL)
2043                     writeLong(os, csize);
2044                 if (locoff0 == ZIP64_MINVAL)
2045                     writeLong(os, locoff);
2046             }
2047             if (elenNTFS != 0) {
2048                 writeShort(os, EXTID_NTFS);
2049                 writeShort(os, elenNTFS - 4);
2050                 writeInt(os, 0);            // reserved
2051                 writeShort(os, 0x0001);     // NTFS attr tag
2052                 writeShort(os, 24);
2053                 writeLong(os, javaToWinTime(mtime));
2054                 writeLong(os, javaToWinTime(atime));
2055                 writeLong(os, javaToWinTime(ctime));
2056             }
2057             if (elenEXTT != 0) {
2058                 writeShort(os, EXTID_EXTT);
2059                 writeShort(os, elenEXTT - 4);
2060                 if (ctime == -1)
2061                     os.write(0x3);          // mtime and atime
2062                 else
2063                     os.write(0x7);          // mtime, atime and ctime
2064                 writeInt(os, javaToUnixTime(mtime));
2065             }
2066             if (extra != null)              // whatever not recognized
2067                 writeBytes(os, extra);
2068             if (comment != null)            //TBD: 0, Math.min(commentBytes.length, 0xffff));
2069                 writeBytes(os, comment);
2070             return CENHDR + nlen + elen + clen + elen64 + elenNTFS + elenEXTT;
2071         }
2072 
2073         ///////////////////// LOC //////////////////////
2074 
2075         int writeLOC(OutputStream os) throws IOException {
2076             writeInt(os, LOCSIG);               // LOC header signature
2077             int version = version();
2078 
2079             byte[] zname = isdir ? toDirectoryPath(name) : name;
2080             int nlen = (zname != null) ? zname.length - 1 : 0; // [0] is slash
2081             int elen = (extra != null) ? extra.length : 0;
2082             boolean foundExtraTime = false;     // if extra timestamp present
2083             int eoff = 0;
2084             int elen64 = 0;
2085             int elenEXTT = 0;
2086             int elenNTFS = 0;
2087             if ((flag & FLAG_DATADESCR) != 0) {
2088                 writeShort(os, version());      // version needed to extract
2089                 writeShort(os, flag);           // general purpose bit flag
2090                 writeShort(os, method);         // compression method
2091                 // last modification time
2092                 writeInt(os, (int)javaToDosTime(mtime));
2093                 // store size, uncompressed size, and crc-32 in data descriptor
2094                 // immediately following compressed entry data
2095                 writeInt(os, 0);
2096                 writeInt(os, 0);
2097                 writeInt(os, 0);
2098             } else {
2099                 if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) {
2100                     elen64 = 20;    //headid(2) + size(2) + size(8) + csize(8)
2101                     writeShort(os, 45);         // ver 4.5 for zip64
2102                 } else {
2103                     writeShort(os, version());  // version needed to extract
2104                 }
2105                 writeShort(os, flag);           // general purpose bit flag
2106                 writeShort(os, method);         // compression method
2107                                                 // last modification time
2108                 writeInt(os, (int)javaToDosTime(mtime));
2109                 writeInt(os, crc);              // crc-32
2110                 if (elen64 != 0) {
2111                     writeInt(os, ZIP64_MINVAL);
2112                     writeInt(os, ZIP64_MINVAL);
2113                 } else {
2114                     writeInt(os, csize);        // compressed size
2115                     writeInt(os, size);         // uncompressed size
2116                 }
2117             }
2118             while (eoff + 4 < elen) {
2119                 int tag = SH(extra, eoff);
2120                 int sz = SH(extra, eoff + 2);
2121                 if (tag == EXTID_EXTT || tag == EXTID_NTFS) {
2122                     foundExtraTime = true;
2123                 }
2124                 eoff += (4 + sz);
2125             }
2126             if (!foundExtraTime) {
2127                 if (isWindows) {
2128                     elenNTFS = 36;              // NTFS, total 36 bytes
2129                 } else {                        // on unix use "ext time"
2130                     elenEXTT = 9;
2131                     if (atime != -1)
2132                         elenEXTT += 4;
2133                     if (ctime != -1)
2134                         elenEXTT += 4;
2135                 }
2136             }
2137             writeShort(os, nlen);
2138             writeShort(os, elen + elen64 + elenNTFS + elenEXTT);
2139             writeBytes(os, zname, 1, nlen);
2140             if (elen64 != 0) {
2141                 writeShort(os, EXTID_ZIP64);
2142                 writeShort(os, 16);
2143                 writeLong(os, size);
2144                 writeLong(os, csize);
2145             }
2146             if (elenNTFS != 0) {
2147                 writeShort(os, EXTID_NTFS);
2148                 writeShort(os, elenNTFS - 4);
2149                 writeInt(os, 0);            // reserved
2150                 writeShort(os, 0x0001);     // NTFS attr tag
2151                 writeShort(os, 24);
2152                 writeLong(os, javaToWinTime(mtime));
2153                 writeLong(os, javaToWinTime(atime));
2154                 writeLong(os, javaToWinTime(ctime));
2155             }
2156             if (elenEXTT != 0) {
2157                 writeShort(os, EXTID_EXTT);
2158                 writeShort(os, elenEXTT - 4);// size for the folowing data block
2159                 int fbyte = 0x1;
2160                 if (atime != -1)           // mtime and atime
2161                     fbyte |= 0x2;
2162                 if (ctime != -1)           // mtime, atime and ctime
2163                     fbyte |= 0x4;
2164                 os.write(fbyte);           // flags byte
2165                 writeInt(os, javaToUnixTime(mtime));
2166                 if (atime != -1)
2167                     writeInt(os, javaToUnixTime(atime));
2168                 if (ctime != -1)
2169                     writeInt(os, javaToUnixTime(ctime));
2170             }
2171             if (extra != null) {
2172                 writeBytes(os, extra);
2173             }
2174             return LOCHDR + nlen + elen + elen64 + elenNTFS + elenEXTT;
2175         }
2176 
2177         // Data Descriptior
2178         int writeEXT(OutputStream os) throws IOException {
2179             writeInt(os, EXTSIG);           // EXT header signature
2180             writeInt(os, crc);              // crc-32
2181             if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) {
2182                 writeLong(os, csize);
2183                 writeLong(os, size);
2184                 return 24;
2185             } else {
2186                 writeInt(os, csize);        // compressed size
2187                 writeInt(os, size);         // uncompressed size
2188                 return 16;
2189             }
2190         }
2191 
2192         // read NTFS, UNIX and ZIP64 data from cen.extra
2193         void readExtra(ZipFileSystem zipfs) throws IOException {
2194             if (extra == null)
2195                 return;
2196             int elen = extra.length;
2197             int off = 0;
2198             int newOff = 0;
2199             while (off + 4 < elen) {
2200                 // extra spec: HeaderID+DataSize+Data
2201                 int pos = off;
2202                 int tag = SH(extra, pos);
2203                 int sz = SH(extra, pos + 2);
2204                 pos += 4;
2205                 if (pos + sz > elen)         // invalid data
2206                     break;
2207                 switch (tag) {
2208                 case EXTID_ZIP64 :
2209                     if (size == ZIP64_MINVAL) {
2210                         if (pos + 8 > elen)  // invalid zip64 extra
2211                             break;           // fields, just skip
2212                         size = LL(extra, pos);
2213                         pos += 8;
2214                     }
2215                     if (csize == ZIP64_MINVAL) {
2216                         if (pos + 8 > elen)
2217                             break;
2218                         csize = LL(extra, pos);
2219                         pos += 8;
2220                     }
2221                     if (locoff == ZIP64_MINVAL) {
2222                         if (pos + 8 > elen)
2223                             break;
2224                         locoff = LL(extra, pos);
2225                         pos += 8;
2226                     }
2227                     break;
2228                 case EXTID_NTFS:
2229                     if (sz < 32)
2230                         break;
2231                     pos += 4;    // reserved 4 bytes
2232                     if (SH(extra, pos) !=  0x0001)
2233                         break;
2234                     if (SH(extra, pos + 2) != 24)
2235                         break;
2236                     // override the loc field, datatime here is
2237                     // more "accurate"
2238                     mtime  = winToJavaTime(LL(extra, pos + 4));
2239                     atime  = winToJavaTime(LL(extra, pos + 12));
2240                     ctime  = winToJavaTime(LL(extra, pos + 20));
2241                     break;
2242                 case EXTID_EXTT:
2243                     // spec says the Extened timestamp in cen only has mtime
2244                     // need to read the loc to get the extra a/ctime, if flag
2245                     // "zipinfo-time" is not specified to false;
2246                     // there is performance cost (move up to loc and read) to
2247                     // access the loc table foreach entry;
2248                     if (zipfs.noExtt) {
2249                         if (sz == 5)
2250                             mtime = unixToJavaTime(LG(extra, pos + 1));
2251                          break;
2252                     }
2253                     byte[] buf = new byte[LOCHDR];
2254                     if (zipfs.readFullyAt(buf, 0, buf.length , locoff)
2255                         != buf.length)
2256                         throw new ZipException("loc: reading failed");
2257                     if (!locSigAt(buf, 0))
2258                         throw new ZipException("loc: wrong sig ->"
2259                                            + Long.toString(getSig(buf, 0), 16));
2260                     int locElen = LOCEXT(buf);
2261                     if (locElen < 9)    // EXTT is at lease 9 bytes
2262                         break;
2263                     int locNlen = LOCNAM(buf);
2264                     buf = new byte[locElen];
2265                     if (zipfs.readFullyAt(buf, 0, buf.length , locoff + LOCHDR + locNlen)
2266                         != buf.length)
2267                         throw new ZipException("loc extra: reading failed");
2268                     int locPos = 0;
2269                     while (locPos + 4 < buf.length) {
2270                         int locTag = SH(buf, locPos);
2271                         int locSZ  = SH(buf, locPos + 2);
2272                         locPos += 4;
2273                         if (locTag  != EXTID_EXTT) {
2274                             locPos += locSZ;
2275                              continue;
2276                         }
2277                         int end = locPos + locSZ - 4;
2278                         int flag = CH(buf, locPos++);
2279                         if ((flag & 0x1) != 0 && locPos <= end) {
2280                             mtime = unixToJavaTime(LG(buf, locPos));
2281                             locPos += 4;
2282                         }
2283                         if ((flag & 0x2) != 0 && locPos <= end) {
2284                             atime = unixToJavaTime(LG(buf, locPos));
2285                             locPos += 4;
2286                         }
2287                         if ((flag & 0x4) != 0 && locPos <= end) {
2288                             ctime = unixToJavaTime(LG(buf, locPos));
2289                             locPos += 4;
2290                         }
2291                         break;
2292                     }
2293                     break;
2294                 default:    // unknown tag
2295                     System.arraycopy(extra, off, extra, newOff, sz + 4);
2296                     newOff += (sz + 4);
2297                 }
2298                 off += (sz + 4);
2299             }
2300             if (newOff != 0 && newOff != extra.length)
2301                 extra = Arrays.copyOf(extra, newOff);
2302             else
2303                 extra = null;
2304         }
2305 
2306         ///////// basic file attributes ///////////
2307         @Override
2308         public FileTime creationTime() {
2309             return FileTime.fromMillis(ctime == -1 ? mtime : ctime);
2310         }
2311 
2312         @Override
2313         public boolean isDirectory() {
2314             return isDir();
2315         }
2316 
2317         @Override
2318         public boolean isOther() {
2319             return false;
2320         }
2321 
2322         @Override
2323         public boolean isRegularFile() {
2324             return !isDir();
2325         }
2326 
2327         @Override
2328         public FileTime lastAccessTime() {
2329             return FileTime.fromMillis(atime == -1 ? mtime : atime);
2330         }
2331 
2332         @Override
2333         public FileTime lastModifiedTime() {
2334             return FileTime.fromMillis(mtime);
2335         }
2336 
2337         @Override
2338         public long size() {
2339             return size;
2340         }
2341 
2342         @Override
2343         public boolean isSymbolicLink() {
2344             return false;
2345         }
2346 
2347         @Override
2348         public Object fileKey() {
2349             return null;
2350         }
2351 
2352         ///////// zip entry attributes ///////////
2353         public long compressedSize() {
2354             return csize;
2355         }
2356 
2357         public long crc() {
2358             return crc;
2359         }
2360 
2361         public int method() {
2362             return method;
2363         }
2364 
2365         public byte[] extra() {
2366             if (extra != null)
2367                 return Arrays.copyOf(extra, extra.length);
2368             return null;
2369         }
2370 
2371         public byte[] comment() {
2372             if (comment != null)
2373                 return Arrays.copyOf(comment, comment.length);
2374             return null;
2375         }
2376 
2377         public String toString() {
2378             StringBuilder sb = new StringBuilder(1024);
2379             Formatter fm = new Formatter(sb);
2380             fm.format("    name            : %s%n", new String(name));
2381             fm.format("    creationTime    : %tc%n", creationTime().toMillis());
2382             fm.format("    lastAccessTime  : %tc%n", lastAccessTime().toMillis());
2383             fm.format("    lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
2384             fm.format("    isRegularFile   : %b%n", isRegularFile());
2385             fm.format("    isDirectory     : %b%n", isDirectory());
2386             fm.format("    isSymbolicLink  : %b%n", isSymbolicLink());
2387             fm.format("    isOther         : %b%n", isOther());
2388             fm.format("    fileKey         : %s%n", fileKey());
2389             fm.format("    size            : %d%n", size());
2390             fm.format("    compressedSize  : %d%n", compressedSize());
2391             fm.format("    crc             : %x%n", crc());
2392             fm.format("    method          : %d%n", method());
2393             fm.close();
2394             return sb.toString();
2395         }
2396     }
2397 
2398     // ZIP directory has two issues:
2399     // (1) ZIP spec does not require the ZIP file to include
2400     //     directory entry
2401     // (2) all entries are not stored/organized in a "tree"
2402     //     structure.
2403     // A possible solution is to build the node tree ourself as
2404     // implemented below.
2405     private IndexNode root;
2406 
2407     // default time stamp for pseudo entries
2408     private long zfsDefaultTimeStamp = System.currentTimeMillis();
2409 
2410     private void removeFromTree(IndexNode inode) {
2411         IndexNode parent = inodes.get(LOOKUPKEY.as(getParent(inode.name)));
2412         IndexNode child = parent.child;
2413         if (child.equals(inode)) {
2414             parent.child = child.sibling;
2415         } else {
2416             IndexNode last = child;
2417             while ((child = child.sibling) != null) {
2418                 if (child.equals(inode)) {
2419                     last.sibling = child.sibling;
2420                     break;
2421                 } else {
2422                     last = child;
2423                 }
2424             }
2425         }
2426     }
2427 
2428     // purely for parent lookup, so we don't have to copy the parent
2429     // name every time
2430     static class ParentLookup extends IndexNode {
2431         int len;
2432         ParentLookup() {}
2433 
2434         final ParentLookup as(byte[] name, int len) { // as a lookup "key"
2435             name(name, len);
2436             return this;
2437         }
2438 
2439         void name(byte[] name, int len) {
2440             this.name = name;
2441             this.len = len;
2442             // calculate the hashcode the same way as Arrays.hashCode() does
2443             int result = 1;
2444             for (int i = 0; i < len; i++)
2445                 result = 31 * result + name[i];
2446             this.hashcode = result;
2447         }
2448 
2449         @Override
2450         public boolean equals(Object other) {
2451             if (!(other instanceof IndexNode)) {
2452                 return false;
2453             }
2454             byte[] oname = ((IndexNode)other).name;
2455             return Arrays.equals(name, 0, len,
2456                                  oname, 0, oname.length);
2457         }
2458 
2459     }
2460 
2461     private void buildNodeTree() throws IOException {
2462         beginWrite();
2463         try {
2464             IndexNode root = new IndexNode(ROOTPATH, true);
2465             IndexNode[] nodes = inodes.keySet().toArray(new IndexNode[0]);
2466             inodes.put(root, root);
2467             ParentLookup lookup = new ParentLookup();
2468             for (IndexNode node : nodes) {
2469                 IndexNode parent;
2470                 while (true) {
2471                     int off = getParentOff(node.name);
2472                     if (off <= 1) {    // parent is root
2473                         node.sibling = root.child;
2474                         root.child = node;
2475                         break;
2476                     }
2477                     lookup = lookup.as(node.name, off);
2478                     if (inodes.containsKey(lookup)) {
2479                         parent = inodes.get(lookup);
2480                         node.sibling = parent.child;
2481                         parent.child = node;
2482                         break;
2483                     }
2484                     // add new pseudo directory entry
2485                     parent = new IndexNode(Arrays.copyOf(node.name, off), true);
2486                     inodes.put(parent, parent);
2487                     node.sibling = parent.child;
2488                     parent.child = node;
2489                     node = parent;
2490                 }
2491             }
2492         } finally {
2493             endWrite();
2494         }
2495     }
2496 }