PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java

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