PageRenderTime 75ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

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

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