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, 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         //
1151         // an extra byte after loc is read, which should be the first byte of the
1152         // 'name' field of the loc. if this byte is '/', which means the original
1153         // entry has an absolute path in original zip/jar file, the e.writeLOC()
1154         // is used to output the loc, in which the leading "/" will be removed
1155         if (readFullyAt(buf, 0, LOCHDR + 1 , locoff) != LOCHDR + 1)
1156             throw new ZipException("loc: reading failed");
1157 
1158         if (updateHeader || LOCNAM(buf) > 0 && buf[LOCHDR] == '/') {
1159             locoff += LOCHDR + LOCNAM(buf) + LOCEXT(buf);  // skip header
1160             size += e.csize;
1161             written = e.writeLOC(os) + size;
1162         } else {
1163             os.write(buf, 0, LOCHDR);    // write out the loc header
1164             locoff += LOCHDR;
1165             // use e.csize,  LOCSIZ(buf) is zero if FLAG_DATADESCR is on
1166             // size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf);
1167             size += LOCNAM(buf) + LOCEXT(buf) + e.csize;
1168             written = LOCHDR + size;
1169         }
1170         int n;
1171         while (size > 0 &&
1172             (n = (int)readFullyAt(buf, 0, buf.length, locoff)) != -1)
1173         {
1174             if (size < n)
1175                 n = (int)size;
1176             os.write(buf, 0, n);
1177             size -= n;
1178             locoff += n;
1179         }
1180         return written;
1181     }
1182 
1183     private long writeEntry(Entry e, OutputStream os, byte[] buf)
1184         throws IOException {
1185 
1186         if (e.bytes == null && e.file == null)    // dir, 0-length data
1187             return 0;
1188 
1189         long written = 0;
1190         try (OutputStream os2 = e.method == METHOD_STORED ?
1191             new EntryOutputStreamCRC32(e, os) : new EntryOutputStreamDef(e, os)) {
1192             if (e.bytes != null) {                 // in-memory
1193                 os2.write(e.bytes, 0, e.bytes.length);
1194             } else if (e.file != null) {           // tmp file
1195                 if (e.type == Entry.NEW || e.type == Entry.FILECH) {
1196                     try (InputStream is = Files.newInputStream(e.file)) {
1197                         is.transferTo(os2);
1198                     }
1199                 }
1200                 Files.delete(e.file);
1201                 tmppaths.remove(e.file);
1202             }
1203         }
1204         written += e.csize;
1205         if ((e.flag & FLAG_DATADESCR) != 0) {
1206             written += e.writeEXT(os);
1207         }
1208         return written;
1209     }
1210 
1211     // sync the zip file system, if there is any udpate
1212     private void sync() throws IOException {
1213 
1214         if (!hasUpdate)
1215             return;
1216         Path tmpFile = createTempFileInSameDirectoryAs(zfpath);
1217         try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(tmpFile, WRITE)))
1218         {
1219             ArrayList<Entry> elist = new ArrayList<>(inodes.size());
1220             long written = 0;
1221             byte[] buf = new byte[8192];
1222             Entry e = null;
1223 
1224             // write loc
1225             for (IndexNode inode : inodes.values()) {
1226                 if (inode instanceof Entry) {    // an updated inode
1227                     e = (Entry)inode;
1228                     try {
1229                         if (e.type == Entry.COPY) {
1230                             // entry copy: the only thing changed is the "name"
1231                             // and "nlen" in LOC header, so we udpate/rewrite the
1232                             // LOC in new file and simply copy the rest (data and
1233                             // ext) without enflating/deflating from the old zip
1234                             // file LOC entry.
1235                             written += copyLOCEntry(e, true, os, written, buf);
1236                         } else {                          // NEW, FILECH or CEN
1237                             e.locoff = written;
1238                             written += e.writeLOC(os);    // write loc header
1239                             written += writeEntry(e, os, buf);
1240                         }
1241                         elist.add(e);
1242                     } catch (IOException x) {
1243                         x.printStackTrace();    // skip any in-accurate entry
1244                     }
1245                 } else {                        // unchanged inode
1246                     if (inode.pos == -1) {
1247                         continue;               // pseudo directory node
1248                     }
1249                     if (inode.name.length == 1 && inode.name[0] == '/') {
1250                         continue;               // no root '/' directory even it
1251                                                 // exits in original zip/jar file.
1252                     }
1253                     e = Entry.readCEN(this, inode);
1254                     try {
1255                         written += copyLOCEntry(e, false, os, written, buf);
1256                         elist.add(e);
1257                     } catch (IOException x) {
1258                         x.printStackTrace();    // skip any wrong entry
1259                     }
1260                 }
1261             }
1262 
1263             // now write back the cen and end table
1264             end.cenoff = written;
1265             for (Entry entry : elist) {
1266                 written += entry.writeCEN(os);
1267             }
1268             end.centot = elist.size();
1269             end.cenlen = written - end.cenoff;
1270             end.write(os, written, forceEnd64);
1271         }
1272 
1273         ch.close();
1274         Files.delete(zfpath);
1275         Files.move(tmpFile, zfpath, REPLACE_EXISTING);
1276         hasUpdate = false;    // clear
1277     }
1278 
1279     IndexNode getInode(byte[] path) {
1280         if (path == null)
1281             throw new NullPointerException("path");
1282         return inodes.get(IndexNode.keyOf(path));
1283     }
1284 
1285     Entry getEntry(byte[] path) throws IOException {
1286         IndexNode inode = getInode(path);
1287         if (inode instanceof Entry)
1288             return (Entry)inode;
1289         if (inode == null || inode.pos == -1)
1290             return null;
1291         return Entry.readCEN(this, inode);
1292     }
1293 
1294     public void deleteFile(byte[] path, boolean failIfNotExists)
1295         throws IOException
1296     {
1297         checkWritable();
1298 
1299         IndexNode inode = getInode(path);
1300         if (inode == null) {
1301             if (path != null && path.length == 0)
1302                 throw new ZipException("root directory </> can't not be delete");
1303             if (failIfNotExists)
1304                 throw new NoSuchFileException(getString(path));
1305         } else {
1306             if (inode.isDir() && inode.child != null)
1307                 throw new DirectoryNotEmptyException(getString(path));
1308             updateDelete(inode);
1309         }
1310     }
1311 
1312     // Returns an out stream for either
1313     // (1) writing the contents of a new entry, if the entry exits, or
1314     // (2) updating/replacing the contents of the specified existing entry.
1315     private OutputStream getOutputStream(Entry e) throws IOException {
1316 
1317         if (e.mtime == -1)
1318             e.mtime = System.currentTimeMillis();
1319         if (e.method == -1)
1320             e.method = defaultMethod;
1321         // store size, compressed size, and crc-32 in datadescr
1322         e.flag = FLAG_DATADESCR;
1323         if (zc.isUTF8())
1324             e.flag |= FLAG_USE_UTF8;
1325         OutputStream os;
1326         if (useTempFile) {
1327             e.file = getTempPathForEntry(null);
1328             os = Files.newOutputStream(e.file, WRITE);
1329         } else {
1330             os = new ByteArrayOutputStream((e.size > 0)? (int)e.size : 8192);
1331         }
1332         return new EntryOutputStream(e, os);
1333     }
1334 
1335     private class EntryOutputStream extends FilterOutputStream {
1336         private Entry e;
1337         private long written;
1338         private boolean isClosed;
1339 
1340         EntryOutputStream(Entry e, OutputStream os) throws IOException {
1341             super(os);
1342             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1343             // this.written = 0;
1344         }
1345 
1346         @Override
1347         public synchronized void write(int b) throws IOException {
1348             out.write(b);
1349             written += 1;
1350         }
1351 
1352         @Override
1353         public synchronized void write(byte b[], int off, int len)
1354                 throws IOException {
1355             out.write(b, off, len);
1356             written += len;
1357         }
1358 
1359         @Override
1360         public synchronized void close() throws IOException {
1361             if (isClosed) {
1362                 return;
1363             }
1364             isClosed = true;
1365             e.size = written;
1366             if (out instanceof ByteArrayOutputStream)
1367                 e.bytes = ((ByteArrayOutputStream)out).toByteArray();
1368             super.close();
1369             update(e);
1370         }
1371     }
1372 
1373     // Wrapper output stream class to write out a "stored" entry.
1374     // (1) this class does not close the underlying out stream when
1375     //     being closed.
1376     // (2) no need to be "synchronized", only used by sync()
1377     private class EntryOutputStreamCRC32 extends FilterOutputStream {
1378         private Entry e;
1379         private CRC32 crc;
1380         private long written;
1381         private boolean isClosed;
1382 
1383         EntryOutputStreamCRC32(Entry e, OutputStream os) throws IOException {
1384             super(os);
1385             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1386             this.crc = new CRC32();
1387         }
1388 
1389         @Override
1390         public void write(int b) throws IOException {
1391             out.write(b);
1392             crc.update(b);
1393             written += 1;
1394         }
1395 
1396         @Override
1397         public void write(byte b[], int off, int len)
1398                 throws IOException {
1399             out.write(b, off, len);
1400             crc.update(b, off, len);
1401             written += len;
1402         }
1403 
1404         @Override
1405         public void close() throws IOException {
1406             if (isClosed)
1407                 return;
1408             isClosed = true;
1409             e.size = e.csize = written;
1410             e.size = crc.getValue();
1411         }
1412     }
1413 
1414     // Wrapper output stream class to write out a "deflated" entry.
1415     // (1) this class does not close the underlying out stream when
1416     //     being closed.
1417     // (2) no need to be "synchronized", only used by sync()
1418     private class EntryOutputStreamDef extends DeflaterOutputStream {
1419         private CRC32 crc;
1420         private Entry e;
1421         private boolean isClosed;
1422 
1423         EntryOutputStreamDef(Entry e, OutputStream os) throws IOException {
1424             super(os, getDeflater());
1425             this.e =  Objects.requireNonNull(e, "Zip entry is null");
1426             this.crc = new CRC32();
1427         }
1428 
1429         @Override
1430         public void write(byte b[], int off, int len)
1431                 throws IOException {
1432             super.write(b, off, len);
1433             crc.update(b, off, len);
1434         }
1435 
1436         @Override
1437         public void close() throws IOException {
1438             if (isClosed)
1439                 return;
1440             isClosed = true;
1441             finish();
1442             e.size  = def.getBytesRead();
1443             e.csize = def.getBytesWritten();
1444             e.crc = crc.getValue();
1445         }
1446     }
1447 
1448     private InputStream getInputStream(Entry e)
1449         throws IOException
1450     {
1451         InputStream eis = null;
1452 
1453         if (e.type == Entry.NEW) {
1454             // now bytes & file is uncompressed.
1455             if (e.bytes != null)
1456                 return new ByteArrayInputStream(e.bytes);
1457             else if (e.file != null)
1458                 return Files.newInputStream(e.file);
1459             else
1460                 throw new ZipException("update entry data is missing");
1461         } else if (e.type == Entry.FILECH) {
1462             // FILECH result is un-compressed.
1463             eis = Files.newInputStream(e.file);
1464             // TBD: wrap to hook close()
1465             // streams.add(eis);
1466             return eis;
1467         } else {  // untouced  CEN or COPY
1468             eis = new EntryInputStream(e, ch);
1469         }
1470         if (e.method == METHOD_DEFLATED) {
1471             // MORE: Compute good size for inflater stream:
1472             long bufSize = e.size + 2; // Inflater likes a bit of slack
1473             if (bufSize > 65536)
1474                 bufSize = 8192;
1475             final long size = e.size;
1476             eis = new InflaterInputStream(eis, getInflater(), (int)bufSize) {
1477                 private boolean isClosed = false;
1478                 public void close() throws IOException {
1479                     if (!isClosed) {
1480                         releaseInflater(inf);
1481                         this.in.close();
1482                         isClosed = true;
1483                         streams.remove(this);
1484                     }
1485                 }
1486                 // Override fill() method to provide an extra "dummy" byte
1487                 // at the end of the input stream. This is required when
1488                 // using the "nowrap" Inflater option. (it appears the new
1489                 // zlib in 7 does not need it, but keep it for now)
1490                 protected void fill() throws IOException {
1491                     if (eof) {
1492                         throw new EOFException(
1493                             "Unexpected end of ZLIB input stream");
1494                     }
1495                     len = this.in.read(buf, 0, buf.length);
1496                     if (len == -1) {
1497                         buf[0] = 0;
1498                         len = 1;
1499                         eof = true;
1500                     }
1501                     inf.setInput(buf, 0, len);
1502                 }
1503                 private boolean eof;
1504 
1505                 public int available() throws IOException {
1506                     if (isClosed)
1507                         return 0;
1508                     long avail = size - inf.getBytesWritten();
1509                     return avail > (long) Integer.MAX_VALUE ?
1510                         Integer.MAX_VALUE : (int) avail;
1511                 }
1512             };
1513         } else if (e.method == METHOD_STORED) {
1514             // TBD: wrap/ it does not seem necessary
1515         } else {
1516             throw new ZipException("invalid compression method");
1517         }
1518         streams.add(eis);
1519         return eis;
1520     }
1521 
1522     // Inner class implementing the input stream used to read
1523     // a (possibly compressed) zip file entry.
1524     private class EntryInputStream extends InputStream {
1525         private final SeekableByteChannel zfch; // local ref to zipfs's "ch". zipfs.ch might
1526                                           // point to a new channel after sync()
1527         private   long pos;               // current position within entry data
1528         protected long rem;               // number of remaining bytes within entry
1529         protected final long size;        // uncompressed size of this entry
1530 
1531         EntryInputStream(Entry e, SeekableByteChannel zfch)
1532             throws IOException
1533         {
1534             this.zfch = zfch;
1535             rem = e.csize;
1536             size = e.size;
1537             pos = e.locoff;
1538             if (pos == -1) {
1539                 Entry e2 = getEntry(e.name);
1540                 if (e2 == null) {
1541                     throw new ZipException("invalid loc for entry <" + e.name + ">");
1542                 }
1543                 pos = e2.locoff;
1544             }
1545             pos = -pos;  // lazy initialize the real data offset
1546         }
1547 
1548         public int read(byte b[], int off, int len) throws IOException {
1549             ensureOpen();
1550             initDataPos();
1551             if (rem == 0) {
1552                 return -1;
1553             }
1554             if (len <= 0) {
1555                 return 0;
1556             }
1557             if (len > rem) {
1558                 len = (int) rem;
1559             }
1560             // readFullyAt()
1561             long n = 0;
1562             ByteBuffer bb = ByteBuffer.wrap(b);
1563             bb.position(off);
1564             bb.limit(off + len);
1565             synchronized(zfch) {
1566                 n = zfch.position(pos).read(bb);
1567             }
1568             if (n > 0) {
1569                 pos += n;
1570                 rem -= n;
1571             }
1572             if (rem == 0) {
1573                 close();
1574             }
1575             return (int)n;
1576         }
1577 
1578         public int read() throws IOException {
1579             byte[] b = new byte[1];
1580             if (read(b, 0, 1) == 1) {
1581                 return b[0] & 0xff;
1582             } else {
1583                 return -1;
1584             }
1585         }
1586 
1587         public long skip(long n) throws IOException {
1588             ensureOpen();
1589             if (n > rem)
1590                 n = rem;
1591             pos += n;
1592             rem -= n;
1593             if (rem == 0) {
1594                 close();
1595             }
1596             return n;
1597         }
1598 
1599         public int available() {
1600             return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem;
1601         }
1602 
1603         public long size() {
1604             return size;
1605         }
1606 
1607         public void close() {
1608             rem = 0;
1609             streams.remove(this);
1610         }
1611 
1612         private void initDataPos() throws IOException {
1613             if (pos <= 0) {
1614                 pos = -pos + locpos;
1615                 byte[] buf = new byte[LOCHDR];
1616                 if (readFullyAt(buf, 0, buf.length, pos) != LOCHDR) {
1617                     throw new ZipException("invalid loc " + pos + " for entry reading");
1618                 }
1619                 pos += LOCHDR + LOCNAM(buf) + LOCEXT(buf);
1620             }
1621         }
1622     }
1623 
1624     static void zerror(String msg) throws ZipException {
1625         throw new ZipException(msg);
1626     }
1627 
1628     // Maxmum number of de/inflater we cache
1629     private final int MAX_FLATER = 20;
1630     // List of available Inflater objects for decompression
1631     private final List<Inflater> inflaters = new ArrayList<>();
1632 
1633     // Gets an inflater from the list of available inflaters or allocates
1634     // a new one.
1635     private Inflater getInflater() {
1636         synchronized (inflaters) {
1637             int size = inflaters.size();
1638             if (size > 0) {
1639                 Inflater inf = inflaters.remove(size - 1);
1640                 return inf;
1641             } else {
1642                 return new Inflater(true);
1643             }
1644         }
1645     }
1646 
1647     // Releases the specified inflater to the list of available inflaters.
1648     private void releaseInflater(Inflater inf) {
1649         synchronized (inflaters) {
1650             if (inflaters.size() < MAX_FLATER) {
1651                 inf.reset();
1652                 inflaters.add(inf);
1653             } else {
1654                 inf.end();
1655             }
1656         }
1657     }
1658 
1659     // List of available Deflater objects for compression
1660     private final List<Deflater> deflaters = new ArrayList<>();
1661 
1662     // Gets an deflater from the list of available deflaters or allocates
1663     // a new one.
1664     private Deflater getDeflater() {
1665         synchronized (deflaters) {
1666             int size = deflaters.size();
1667             if (size > 0) {
1668                 Deflater def = deflaters.remove(size - 1);
1669                 return def;
1670             } else {
1671                 return new Deflater(Deflater.DEFAULT_COMPRESSION, true);
1672             }
1673         }
1674     }
1675 
1676     // Releases the specified inflater to the list of available inflaters.
1677     private void releaseDeflater(Deflater def) {
1678         synchronized (deflaters) {
1679             if (inflaters.size() < MAX_FLATER) {
1680                def.reset();
1681                deflaters.add(def);
1682             } else {
1683                def.end();
1684             }
1685         }
1686     }
1687 
1688     // End of central directory record
1689     static class END {
1690         // these 2 fields are not used by anyone and write() uses "0"
1691         // int  disknum;
1692         // int  sdisknum;
1693         int  endsub;     // endsub
1694         int  centot;     // 4 bytes
1695         long cenlen;     // 4 bytes
1696         long cenoff;     // 4 bytes
1697         int  comlen;     // comment length
1698         byte[] comment;
1699 
1700         /* members of Zip64 end of central directory locator */
1701         // int diskNum;
1702         long endpos;
1703         // int disktot;
1704 
1705         void write(OutputStream os, long offset, boolean forceEnd64) throws IOException {
1706             boolean hasZip64 = forceEnd64; // false;
1707             long xlen = cenlen;
1708             long xoff = cenoff;
1709             if (xlen >= ZIP64_MINVAL) {
1710                 xlen = ZIP64_MINVAL;
1711                 hasZip64 = true;
1712             }
1713             if (xoff >= ZIP64_MINVAL) {
1714                 xoff = ZIP64_MINVAL;
1715                 hasZip64 = true;
1716             }
1717             int count = centot;
1718             if (count >= ZIP64_MINVAL32) {
1719                 count = ZIP64_MINVAL32;
1720                 hasZip64 = true;
1721             }
1722             if (hasZip64) {
1723                 long off64 = offset;
1724                 //zip64 end of central directory record
1725                 writeInt(os, ZIP64_ENDSIG);       // zip64 END record signature
1726                 writeLong(os, ZIP64_ENDHDR - 12); // size of zip64 end
1727                 writeShort(os, 45);               // version made by
1728                 writeShort(os, 45);               // version needed to extract
1729                 writeInt(os, 0);                  // number of this disk
1730                 writeInt(os, 0);                  // central directory start disk
1731                 writeLong(os, centot);            // number of directory entries on disk
1732                 writeLong(os, centot);            // number of directory entries
1733                 writeLong(os, cenlen);            // length of central directory
1734                 writeLong(os, cenoff);            // offset of central directory
1735 
1736                 //zip64 end of central directory locator
1737                 writeInt(os, ZIP64_LOCSIG);       // zip64 END locator signature
1738                 writeInt(os, 0);                  // zip64 END start disk
1739                 writeLong(os, off64);             // offset of zip64 END
1740                 writeInt(os, 1);                  // total number of disks (?)
1741             }
1742             writeInt(os, ENDSIG);                 // END record signature
1743             writeShort(os, 0);                    // number of this disk
1744             writeShort(os, 0);                    // central directory start disk
1745             writeShort(os, count);                // number of directory entries on disk
1746             writeShort(os, count);                // total number of directory entries
1747             writeInt(os, xlen);                   // length of central directory
1748             writeInt(os, xoff);                   // offset of central directory
1749             if (comment != null) {            // zip file comment
1750                 writeShort(os, comment.length);
1751                 writeBytes(os, comment);
1752             } else {
1753                 writeShort(os, 0);
1754             }
1755         }
1756     }
1757 
1758     // Internal node that links a "name" to its pos in cen table.
1759     // The node itself can be used as a "key" to lookup itself in
1760     // the HashMap inodes.
1761     static class IndexNode {
1762         byte[] name;
1763         int    hashcode;  // node is hashable/hashed by its name
1764         int    pos = -1;  // position in cen table, -1 menas the
1765                           // entry does not exists in zip file
1766         boolean isdir;
1767 
1768         IndexNode(byte[] name, boolean isdir) {
1769             name(name);
1770             this.isdir = isdir;
1771             this.pos = -1;
1772         }
1773 
1774         IndexNode(byte[] name, int pos) {
1775             name(name);
1776             this.pos = pos;
1777         }
1778 
1779         // constructor for cenInit() (1) remove tailing '/' (2) pad leading '/'
1780         IndexNode(byte[] cen, int pos, int nlen) {
1781             int noff = pos + CENHDR;
1782             if (cen[noff + nlen - 1] == '/') {
1783                 isdir = true;
1784                 nlen--;
1785             }
1786             if (nlen > 0 && cen[noff] == '/') {
1787                 name = Arrays.copyOfRange(cen, noff, noff + nlen);
1788             } else {
1789                 name = new byte[nlen + 1];
1790                 System.arraycopy(cen, noff, name, 1, nlen);
1791                 name[0] = '/';
1792             }
1793             name(name);
1794             this.pos = pos;
1795         }
1796 
1797         private static final ThreadLocal<IndexNode> cachedKey = new ThreadLocal<>();
1798 
1799         final static IndexNode keyOf(byte[] name) { // get a lookup key;
1800             IndexNode key = cachedKey.get();
1801             if (key == null) {
1802                 key = new IndexNode(name, -1);
1803                 cachedKey.set(key);
1804             }
1805             return key.as(name);
1806         }
1807 
1808         final void name(byte[] name) {
1809             this.name = name;
1810             this.hashcode = Arrays.hashCode(name);
1811         }
1812 
1813         final IndexNode as(byte[] name) {           // reuse the node, mostly
1814             name(name);                             // as a lookup "key"
1815             return this;
1816         }
1817 
1818         boolean isDir() {
1819             return isdir;
1820         }
1821 
1822         public boolean equals(Object other) {
1823             if (!(other instanceof IndexNode)) {
1824                 return false;
1825             }
1826             if (other instanceof ParentLookup) {
1827                 return ((ParentLookup)other).equals(this);
1828             }
1829             return Arrays.equals(name, ((IndexNode)other).name);
1830         }
1831 
1832         public int hashCode() {
1833             return hashcode;
1834         }
1835 
1836         IndexNode() {}
1837         IndexNode sibling;
1838         IndexNode child;  // 1st child
1839     }
1840 
1841     static class Entry extends IndexNode implements ZipFileAttributes {
1842 
1843         static final int CEN    = 1;  // entry read from cen
1844         static final int NEW    = 2;  // updated contents in bytes or file
1845         static final int FILECH = 3;  // fch update in "file"
1846         static final int COPY   = 4;  // copy of a CEN entry
1847 
1848         byte[] bytes;                 // updated content bytes
1849         Path   file;                  // use tmp file to store bytes;
1850         int    type = CEN;            // default is the entry read from cen
1851 
1852         // entry attributes
1853         int    version;
1854         int    flag;
1855         int    method = -1;    // compression method
1856         long   mtime  = -1;    // last modification time (in DOS time)
1857         long   atime  = -1;    // last access time
1858         long   ctime  = -1;    // create time
1859         long   crc    = -1;    // crc-32 of entry data
1860         long   csize  = -1;    // compressed size of entry data
1861         long   size   = -1;    // uncompressed size of entry data
1862         byte[] extra;
1863 
1864         // cen
1865 
1866         // these fields are not used by anyone and writeCEN uses "0"
1867         // int    versionMade;
1868         // int    disk;
1869         // int    attrs;
1870         // long   attrsEx;
1871         long   locoff;
1872         byte[] comment;
1873 
1874         Entry() {}
1875 
1876         Entry(byte[] name, boolean isdir, int method) {
1877             name(name);
1878             this.isdir = isdir;
1879             this.mtime  = this.ctime = this.atime = System.currentTimeMillis();
1880             this.crc    = 0;
1881             this.size   = 0;
1882             this.csize  = 0;
1883             this.method = method;
1884         }
1885 
1886         Entry(byte[] name, int type, boolean isdir, int method) {
1887             this(name, isdir, method);
1888             this.type = type;
1889         }
1890 
1891         Entry (Entry e, int type) {
1892             name(e.name);
1893             this.isdir     = e.isdir;
1894             this.version   = e.version;
1895             this.ctime     = e.ctime;
1896             this.atime     = e.atime;
1897             this.mtime     = e.mtime;
1898             this.crc       = e.crc;
1899             this.size      = e.size;
1900             this.csize     = e.csize;
1901             this.method    = e.method;
1902             this.extra     = e.extra;
1903             /*
1904             this.versionMade = e.versionMade;
1905             this.disk      = e.disk;
1906             this.attrs     = e.attrs;
1907             this.attrsEx   = e.attrsEx;
1908             */
1909             this.locoff    = e.locoff;
1910             this.comment   = e.comment;
1911             this.type      = type;
1912         }
1913 
1914         Entry (byte[] name, Path file, int type) {
1915             this(name, type, false, METHOD_STORED);
1916             this.file = file;
1917         }
1918 
1919         int version() throws ZipException {
1920             if (method == METHOD_DEFLATED)
1921                 return 20;
1922             else if (method == METHOD_STORED)
1923                 return 10;
1924             throw new ZipException("unsupported compression method");
1925         }
1926 
1927         ///////////////////// CEN //////////////////////
1928         static Entry readCEN(ZipFileSystem zipfs, IndexNode inode)
1929             throws IOException
1930         {
1931             return new Entry().cen(zipfs, inode);
1932         }
1933 
1934         private Entry cen(ZipFileSystem zipfs, IndexNode inode)
1935             throws IOException
1936         {
1937             byte[] cen = zipfs.cen;
1938             int pos = inode.pos;
1939             if (!cenSigAt(cen, pos))
1940                 zerror("invalid CEN header (bad signature)");
1941             version     = CENVER(cen, pos);
1942             flag        = CENFLG(cen, pos);
1943             method      = CENHOW(cen, pos);
1944             mtime       = dosToJavaTime(CENTIM(cen, pos));
1945             crc         = CENCRC(cen, pos);
1946             csize       = CENSIZ(cen, pos);
1947             size        = CENLEN(cen, pos);
1948             int nlen    = CENNAM(cen, pos);
1949             int elen    = CENEXT(cen, pos);
1950             int clen    = CENCOM(cen, pos);
1951             /*
1952             versionMade = CENVEM(cen, pos);
1953             disk        = CENDSK(cen, pos);
1954             attrs       = CENATT(cen, pos);
1955             attrsEx     = CENATX(cen, pos);
1956             */
1957             locoff      = CENOFF(cen, pos);
1958             pos += CENHDR;
1959             this.name = inode.name;
1960             this.isdir = inode.isdir;
1961             this.hashcode = inode.hashcode;
1962 
1963             pos += nlen;
1964             if (elen > 0) {
1965                 extra = Arrays.copyOfRange(cen, pos, pos + elen);
1966                 pos += elen;
1967                 readExtra(zipfs);
1968             }
1969             if (clen > 0) {
1970                 comment = Arrays.copyOfRange(cen, pos, pos + clen);
1971             }
1972             return this;
1973         }
1974 
1975         int writeCEN(OutputStream os) throws IOException
1976         {
1977             int written  = CENHDR;
1978             int version0 = version();
1979             long csize0  = csize;
1980             long size0   = size;
1981             long locoff0 = locoff;
1982             int elen64   = 0;                // extra for ZIP64
1983             int elenNTFS = 0;                // extra for NTFS (a/c/mtime)
1984             int elenEXTT = 0;                // extra for Extended Timestamp
1985             boolean foundExtraTime = false;  // if time stamp NTFS, EXTT present
1986 
1987             byte[] zname = isdir ? toDirectoryPath(name) : name;
1988 
1989             // confirm size/length
1990             int nlen = (zname != null) ? zname.length - 1 : 0;  // name has [0] as "slash"
1991             int elen = (extra != null) ? extra.length : 0;
1992             int eoff = 0;
1993             int clen = (comment != null) ? comment.length : 0;
1994             if (csize >= ZIP64_MINVAL) {
1995                 csize0 = ZIP64_MINVAL;
1996                 elen64 += 8;                 // csize(8)
1997             }
1998             if (size >= ZIP64_MINVAL) {
1999                 size0 = ZIP64_MINVAL;        // size(8)
2000                 elen64 += 8;
2001             }
2002             if (locoff >= ZIP64_MINVAL) {
2003                 locoff0 = ZIP64_MINVAL;
2004                 elen64 += 8;                 // offset(8)
2005             }
2006             if (elen64 != 0) {
2007                 elen64 += 4;                 // header and data sz 4 bytes
2008             }
2009             while (eoff + 4 < elen) {
2010                 int tag = SH(extra, eoff);
2011                 int sz = SH(extra, eoff + 2);
2012                 if (tag == EXTID_EXTT || tag == EXTID_NTFS) {
2013                     foundExtraTime = true;
2014                 }
2015                 eoff += (4 + sz);
2016             }
2017             if (!foundExtraTime) {
2018                 if (isWindows) {             // use NTFS
2019                     elenNTFS = 36;           // total 36 bytes
2020                 } else {                     // Extended Timestamp otherwise
2021                     elenEXTT = 9;            // only mtime in cen
2022                 }
2023             }
2024             writeInt(os, CENSIG);            // CEN header signature
2025             if (elen64 != 0) {
2026                 writeShort(os, 45);          // ver 4.5 for zip64
2027                 writeShort(os, 45);
2028             } else {
2029                 writeShort(os, version0);    // version made by
2030                 writeShort(os, version0);    // version needed to extract
2031             }
2032             writeShort(os, flag);            // general purpose bit flag
2033             writeShort(os, method);          // compression method
2034                                              // last modification time
2035             writeInt(os, (int)javaToDosTime(mtime));
2036             writeInt(os, crc);               // crc-32
2037             writeInt(os, csize0);            // compressed size
2038             writeInt(os, size0);             // uncompressed size
2039             writeShort(os, nlen);
2040             writeShort(os, elen + elen64 + elenNTFS + elenEXTT);
2041 
2042             if (comment != null) {
2043                 writeShort(os, Math.min(clen, 0xffff));
2044             } else {
2045                 writeShort(os, 0);
2046             }
2047             writeShort(os, 0);              // starting disk number
2048             writeShort(os, 0);              // internal file attributes (unused)
2049             writeInt(os, 0);                // external file attributes (unused)
2050             writeInt(os, locoff0);          // relative offset of local header
2051             writeBytes(os, zname, 1, nlen);
2052             if (elen64 != 0) {
2053                 writeShort(os, EXTID_ZIP64);// Zip64 extra
2054                 writeShort(os, elen64 - 4); // size of "this" extra block
2055                 if (size0 == ZIP64_MINVAL)
2056                     writeLong(os, size);
2057                 if (csize0 == ZIP64_MINVAL)
2058                     writeLong(os, csize);
2059                 if (locoff0 == ZIP64_MINVAL)
2060                     writeLong(os, locoff);
2061             }
2062             if (elenNTFS != 0) {
2063                 writeShort(os, EXTID_NTFS);
2064                 writeShort(os, elenNTFS - 4);
2065                 writeInt(os, 0);            // reserved
2066                 writeShort(os, 0x0001);     // NTFS attr tag
2067                 writeShort(os, 24);
2068                 writeLong(os, javaToWinTime(mtime));
2069                 writeLong(os, javaToWinTime(atime));
2070                 writeLong(os, javaToWinTime(ctime));
2071             }
2072             if (elenEXTT != 0) {
2073                 writeShort(os, EXTID_EXTT);
2074                 writeShort(os, elenEXTT - 4);
2075                 if (ctime == -1)
2076                     os.write(0x3);          // mtime and atime
2077                 else
2078                     os.write(0x7);          // mtime, atime and ctime
2079                 writeInt(os, javaToUnixTime(mtime));
2080             }
2081             if (extra != null)              // whatever not recognized
2082                 writeBytes(os, extra);
2083             if (comment != null)            //TBD: 0, Math.min(commentBytes.length, 0xffff));
2084                 writeBytes(os, comment);
2085             return CENHDR + nlen + elen + clen + elen64 + elenNTFS + elenEXTT;
2086         }
2087 
2088         ///////////////////// LOC //////////////////////
2089 
2090         int writeLOC(OutputStream os) throws IOException {
2091             writeInt(os, LOCSIG);               // LOC header signature
2092             int version = version();
2093 
2094             byte[] zname = isdir ? toDirectoryPath(name) : name;
2095             int nlen = (zname != null) ? zname.length - 1 : 0; // [0] is slash
2096             int elen = (extra != null) ? extra.length : 0;
2097             boolean foundExtraTime = false;     // if extra timestamp present
2098             int eoff = 0;
2099             int elen64 = 0;
2100             int elenEXTT = 0;
2101             int elenNTFS = 0;
2102             if ((flag & FLAG_DATADESCR) != 0) {
2103                 writeShort(os, version());      // version needed to extract
2104                 writeShort(os, flag);           // general purpose bit flag
2105                 writeShort(os, method);         // compression method
2106                 // last modification time
2107                 writeInt(os, (int)javaToDosTime(mtime));
2108                 // store size, uncompressed size, and crc-32 in data descriptor
2109                 // immediately following compressed entry data
2110                 writeInt(os, 0);
2111                 writeInt(os, 0);
2112                 writeInt(os, 0);
2113             } else {
2114                 if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) {
2115                     elen64 = 20;    //headid(2) + size(2) + size(8) + csize(8)
2116                     writeShort(os, 45);         // ver 4.5 for zip64
2117                 } else {
2118                     writeShort(os, version());  // version needed to extract
2119                 }
2120                 writeShort(os, flag);           // general purpose bit flag
2121                 writeShort(os, method);         // compression method
2122                                                 // last modification time
2123                 writeInt(os, (int)javaToDosTime(mtime));
2124                 writeInt(os, crc);              // crc-32
2125                 if (elen64 != 0) {
2126                     writeInt(os, ZIP64_MINVAL);
2127                     writeInt(os, ZIP64_MINVAL);
2128                 } else {
2129                     writeInt(os, csize);        // compressed size
2130                     writeInt(os, size);         // uncompressed size
2131                 }
2132             }
2133             while (eoff + 4 < elen) {
2134                 int tag = SH(extra, eoff);
2135                 int sz = SH(extra, eoff + 2);
2136                 if (tag == EXTID_EXTT || tag == EXTID_NTFS) {
2137                     foundExtraTime = true;
2138                 }
2139                 eoff += (4 + sz);
2140             }
2141             if (!foundExtraTime) {
2142                 if (isWindows) {
2143                     elenNTFS = 36;              // NTFS, total 36 bytes
2144                 } else {                        // on unix use "ext time"
2145                     elenEXTT = 9;
2146                     if (atime != -1)
2147                         elenEXTT += 4;
2148                     if (ctime != -1)
2149                         elenEXTT += 4;
2150                 }
2151             }
2152             writeShort(os, nlen);
2153             writeShort(os, elen + elen64 + elenNTFS + elenEXTT);
2154             writeBytes(os, zname, 1, nlen);
2155             if (elen64 != 0) {
2156                 writeShort(os, EXTID_ZIP64);
2157                 writeShort(os, 16);
2158                 writeLong(os, size);
2159                 writeLong(os, csize);
2160             }
2161             if (elenNTFS != 0) {
2162                 writeShort(os, EXTID_NTFS);
2163                 writeShort(os, elenNTFS - 4);
2164                 writeInt(os, 0);            // reserved
2165                 writeShort(os, 0x0001);     // NTFS attr tag
2166                 writeShort(os, 24);
2167                 writeLong(os, javaToWinTime(mtime));
2168                 writeLong(os, javaToWinTime(atime));
2169                 writeLong(os, javaToWinTime(ctime));
2170             }
2171             if (elenEXTT != 0) {
2172                 writeShort(os, EXTID_EXTT);
2173                 writeShort(os, elenEXTT - 4);// size for the folowing data block
2174                 int fbyte = 0x1;
2175                 if (atime != -1)           // mtime and atime
2176                     fbyte |= 0x2;
2177                 if (ctime != -1)           // mtime, atime and ctime
2178                     fbyte |= 0x4;
2179                 os.write(fbyte);           // flags byte
2180                 writeInt(os, javaToUnixTime(mtime));
2181                 if (atime != -1)
2182                     writeInt(os, javaToUnixTime(atime));
2183                 if (ctime != -1)
2184                     writeInt(os, javaToUnixTime(ctime));
2185             }
2186             if (extra != null) {
2187                 writeBytes(os, extra);
2188             }
2189             return LOCHDR + nlen + elen + elen64 + elenNTFS + elenEXTT;
2190         }
2191 
2192         // Data Descriptior
2193         int writeEXT(OutputStream os) throws IOException {
2194             writeInt(os, EXTSIG);           // EXT header signature
2195             writeInt(os, crc);              // crc-32
2196             if (csize >= ZIP64_MINVAL || size >= ZIP64_MINVAL) {
2197                 writeLong(os, csize);
2198                 writeLong(os, size);
2199                 return 24;
2200             } else {
2201                 writeInt(os, csize);        // compressed size
2202                 writeInt(os, size);         // uncompressed size
2203                 return 16;
2204             }
2205         }
2206 
2207         // read NTFS, UNIX and ZIP64 data from cen.extra
2208         void readExtra(ZipFileSystem zipfs) throws IOException {
2209             if (extra == null)
2210                 return;
2211             int elen = extra.length;
2212             int off = 0;
2213             int newOff = 0;
2214             while (off + 4 < elen) {
2215                 // extra spec: HeaderID+DataSize+Data
2216                 int pos = off;
2217                 int tag = SH(extra, pos);
2218                 int sz = SH(extra, pos + 2);
2219                 pos += 4;
2220                 if (pos + sz > elen)         // invalid data
2221                     break;
2222                 switch (tag) {
2223                 case EXTID_ZIP64 :
2224                     if (size == ZIP64_MINVAL) {
2225                         if (pos + 8 > elen)  // invalid zip64 extra
2226                             break;           // fields, just skip
2227                         size = LL(extra, pos);
2228                         pos += 8;
2229                     }
2230                     if (csize == ZIP64_MINVAL) {
2231                         if (pos + 8 > elen)
2232                             break;
2233                         csize = LL(extra, pos);
2234                         pos += 8;
2235                     }
2236                     if (locoff == ZIP64_MINVAL) {
2237                         if (pos + 8 > elen)
2238                             break;
2239                         locoff = LL(extra, pos);
2240                         pos += 8;
2241                     }
2242                     break;
2243                 case EXTID_NTFS:
2244                     if (sz < 32)
2245                         break;
2246                     pos += 4;    // reserved 4 bytes
2247                     if (SH(extra, pos) !=  0x0001)
2248                         break;
2249                     if (SH(extra, pos + 2) != 24)
2250                         break;
2251                     // override the loc field, datatime here is
2252                     // more "accurate"
2253                     mtime  = winToJavaTime(LL(extra, pos + 4));
2254                     atime  = winToJavaTime(LL(extra, pos + 12));
2255                     ctime  = winToJavaTime(LL(extra, pos + 20));
2256                     break;
2257                 case EXTID_EXTT:
2258                     // spec says the Extened timestamp in cen only has mtime
2259                     // need to read the loc to get the extra a/ctime, if flag
2260                     // "zipinfo-time" is not specified to false;
2261                     // there is performance cost (move up to loc and read) to
2262                     // access the loc table foreach entry;
2263                     if (zipfs.noExtt) {
2264                         if (sz == 5)
2265                             mtime = unixToJavaTime(LG(extra, pos + 1));
2266                          break;
2267                     }
2268                     byte[] buf = new byte[LOCHDR];
2269                     if (zipfs.readFullyAt(buf, 0, buf.length , locoff)
2270                         != buf.length)
2271                         throw new ZipException("loc: reading failed");
2272                     if (!locSigAt(buf, 0))
2273                         throw new ZipException("loc: wrong sig ->"
2274                                            + Long.toString(getSig(buf, 0), 16));
2275                     int locElen = LOCEXT(buf);
2276                     if (locElen < 9)    // EXTT is at lease 9 bytes
2277                         break;
2278                     int locNlen = LOCNAM(buf);
2279                     buf = new byte[locElen];
2280                     if (zipfs.readFullyAt(buf, 0, buf.length , locoff + LOCHDR + locNlen)
2281                         != buf.length)
2282                         throw new ZipException("loc extra: reading failed");
2283                     int locPos = 0;
2284                     while (locPos + 4 < buf.length) {
2285                         int locTag = SH(buf, locPos);
2286                         int locSZ  = SH(buf, locPos + 2);
2287                         locPos += 4;
2288                         if (locTag  != EXTID_EXTT) {
2289                             locPos += locSZ;
2290                              continue;
2291                         }
2292                         int end = locPos + locSZ - 4;
2293                         int flag = CH(buf, locPos++);
2294                         if ((flag & 0x1) != 0 && locPos <= end) {
2295                             mtime = unixToJavaTime(LG(buf, locPos));
2296                             locPos += 4;
2297                         }
2298                         if ((flag & 0x2) != 0 && locPos <= end) {
2299                             atime = unixToJavaTime(LG(buf, locPos));
2300                             locPos += 4;
2301                         }
2302                         if ((flag & 0x4) != 0 && locPos <= end) {
2303                             ctime = unixToJavaTime(LG(buf, locPos));
2304                             locPos += 4;
2305                         }
2306                         break;
2307                     }
2308                     break;
2309                 default:    // unknown tag
2310                     System.arraycopy(extra, off, extra, newOff, sz + 4);
2311                     newOff += (sz + 4);
2312                 }
2313                 off += (sz + 4);
2314             }
2315             if (newOff != 0 && newOff != extra.length)
2316                 extra = Arrays.copyOf(extra, newOff);
2317             else
2318                 extra = null;
2319         }
2320 
2321         ///////// basic file attributes ///////////
2322         @Override
2323         public FileTime creationTime() {
2324             return FileTime.fromMillis(ctime == -1 ? mtime : ctime);
2325         }
2326 
2327         @Override
2328         public boolean isDirectory() {
2329             return isDir();
2330         }
2331 
2332         @Override
2333         public boolean isOther() {
2334             return false;
2335         }
2336 
2337         @Override
2338         public boolean isRegularFile() {
2339             return !isDir();
2340         }
2341 
2342         @Override
2343         public FileTime lastAccessTime() {
2344             return FileTime.fromMillis(atime == -1 ? mtime : atime);
2345         }
2346 
2347         @Override
2348         public FileTime lastModifiedTime() {
2349             return FileTime.fromMillis(mtime);
2350         }
2351 
2352         @Override
2353         public long size() {
2354             return size;
2355         }
2356 
2357         @Override
2358         public boolean isSymbolicLink() {
2359             return false;
2360         }
2361 
2362         @Override
2363         public Object fileKey() {
2364             return null;
2365         }
2366 
2367         ///////// zip entry attributes ///////////
2368         public long compressedSize() {
2369             return csize;
2370         }
2371 
2372         public long crc() {
2373             return crc;
2374         }
2375 
2376         public int method() {
2377             return method;
2378         }
2379 
2380         public byte[] extra() {
2381             if (extra != null)
2382                 return Arrays.copyOf(extra, extra.length);
2383             return null;
2384         }
2385 
2386         public byte[] comment() {
2387             if (comment != null)
2388                 return Arrays.copyOf(comment, comment.length);
2389             return null;
2390         }
2391 
2392         public String toString() {
2393             StringBuilder sb = new StringBuilder(1024);
2394             Formatter fm = new Formatter(sb);
2395             fm.format("    name            : %s%n", new String(name));
2396             fm.format("    creationTime    : %tc%n", creationTime().toMillis());
2397             fm.format("    lastAccessTime  : %tc%n", lastAccessTime().toMillis());
2398             fm.format("    lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
2399             fm.format("    isRegularFile   : %b%n", isRegularFile());
2400             fm.format("    isDirectory     : %b%n", isDirectory());
2401             fm.format("    isSymbolicLink  : %b%n", isSymbolicLink());
2402             fm.format("    isOther         : %b%n", isOther());
2403             fm.format("    fileKey         : %s%n", fileKey());
2404             fm.format("    size            : %d%n", size());
2405             fm.format("    compressedSize  : %d%n", compressedSize());
2406             fm.format("    crc             : %x%n", crc());
2407             fm.format("    method          : %d%n", method());
2408             fm.close();
2409             return sb.toString();
2410         }
2411     }
2412 
2413     // ZIP directory has two issues:
2414     // (1) ZIP spec does not require the ZIP file to include
2415     //     directory entry
2416     // (2) all entries are not stored/organized in a "tree"
2417     //     structure.
2418     // A possible solution is to build the node tree ourself as
2419     // implemented below.
2420     private IndexNode root;
2421 
2422     // default time stamp for pseudo entries
2423     private long zfsDefaultTimeStamp = System.currentTimeMillis();
2424 
2425     private void removeFromTree(IndexNode inode) {
2426         IndexNode parent = inodes.get(LOOKUPKEY.as(getParent(inode.name)));
2427         IndexNode child = parent.child;
2428         if (child.equals(inode)) {
2429             parent.child = child.sibling;
2430         } else {
2431             IndexNode last = child;
2432             while ((child = child.sibling) != null) {
2433                 if (child.equals(inode)) {
2434                     last.sibling = child.sibling;
2435                     break;
2436                 } else {
2437                     last = child;
2438                 }
2439             }
2440         }
2441     }
2442 
2443     // purely for parent lookup, so we don't have to copy the parent
2444     // name every time
2445     static class ParentLookup extends IndexNode {
2446         int len;
2447         ParentLookup() {}
2448 
2449         final ParentLookup as(byte[] name, int len) { // as a lookup "key"
2450             name(name, len);
2451             return this;
2452         }
2453 
2454         void name(byte[] name, int len) {
2455             this.name = name;
2456             this.len = len;
2457             // calculate the hashcode the same way as Arrays.hashCode() does
2458             int result = 1;
2459             for (int i = 0; i < len; i++)
2460                 result = 31 * result + name[i];
2461             this.hashcode = result;
2462         }
2463 
2464         @Override
2465         public boolean equals(Object other) {
2466             if (!(other instanceof IndexNode)) {
2467                 return false;
2468             }
2469             byte[] oname = ((IndexNode)other).name;
2470             return Arrays.equals(name, 0, len,
2471                                  oname, 0, oname.length);
2472         }
2473 
2474     }
2475 
2476     private void buildNodeTree() throws IOException {
2477         beginWrite();
2478         try {
2479             IndexNode root = inodes.get(LOOKUPKEY.as(ROOTPATH));
2480             if (root == null) {
2481                 root = new IndexNode(ROOTPATH, true);
2482             } else {
2483                 inodes.remove(root);
2484             }
2485             IndexNode[] nodes = inodes.keySet().toArray(new IndexNode[0]);
2486             inodes.put(root, root);
2487             ParentLookup lookup = new ParentLookup();
2488             for (IndexNode node : nodes) {
2489                 IndexNode parent;
2490                 while (true) {
2491                     int off = getParentOff(node.name);
2492                     if (off <= 1) {    // parent is root
2493                         node.sibling = root.child;
2494                         root.child = node;
2495                         break;
2496                     }
2497                     lookup = lookup.as(node.name, off);
2498                     if (inodes.containsKey(lookup)) {
2499                         parent = inodes.get(lookup);
2500                         node.sibling = parent.child;
2501                         parent.child = node;
2502                         break;
2503                     }
2504                     // add new pseudo directory entry
2505                     parent = new IndexNode(Arrays.copyOf(node.name, off), true);
2506                     inodes.put(parent, parent);
2507                     node.sibling = parent.child;
2508                     parent.child = node;
2509                     node = parent;
2510                 }
2511             }
2512         } finally {
2513             endWrite();
2514         }
2515     }
2516 }