PageRenderTime 66ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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.newOutputStre

Large files files are truncated, but you can click here to view the full file