PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/sreilly/openjdk7u-jdk
Java | 2354 lines | 1986 code | 172 blank | 196 comment | 501 complexity | f67ee25f1ff4422c13ff021789f2e871 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.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. /*
  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 not "rename", just take the data
  430. if (eSrc.bytes != null)
  431. u.bytes = Arrays.copyOf(eSrc.bytes, eSrc.bytes.length);
  432. else if (eSrc.file != null) {
  433. u.file = getTempPathForEntry(null);
  434. Files.copy(eSrc.file, u.file, REPLACE_EXISTING);
  435. }
  436. }
  437. }
  438. if (!hasCopyAttrs)
  439. u.mtime = u.atime= u.ctime = System.currentTimeMillis();
  440. update(u);
  441. if (deletesrc)
  442. updateDelete(eSrc);
  443. } finally {
  444. endWrite();
  445. }
  446. }
  447. // Returns an output stream for writing the contents into the specified
  448. // entry.
  449. OutputStream newOutputStream(byte[] path, OpenOption... options)
  450. throws IOException
  451. {
  452. checkWritable();
  453. boolean hasCreateNew = false;
  454. boolean hasCreate = false;
  455. boolean hasAppend = false;
  456. for (OpenOption opt: options) {
  457. if (opt == READ)
  458. throw new IllegalArgumentException("READ not allowed");
  459. if (opt == CREATE_NEW)
  460. hasCreateNew = true;
  461. if (opt == CREATE)
  462. hasCreate = true;
  463. if (opt == APPEND)
  464. hasAppend = true;
  465. }
  466. beginRead(); // only need a readlock, the "update()" will
  467. try { // try to obtain a writelock when the os is
  468. ensureOpen(); // being closed.
  469. Entry e = getEntry0(path);
  470. if (e != null) {
  471. if (e.isDir() || hasCreateNew)
  472. throw new FileAlreadyExistsException(getString(path));
  473. if (hasAppend) {
  474. InputStream is = getInputStream(e);
  475. OutputStream os = getOutputStream(new Entry(e, Entry.NEW));
  476. copyStream(is, os);
  477. is.close();
  478. return os;
  479. }
  480. return getOutputStream(new Entry(e, Entry.NEW));
  481. } else {
  482. if (!hasCreate && !hasCreateNew)
  483. throw new NoSuchFileException(getString(path));
  484. checkParents(path);
  485. return getOutputStream(new Entry(path, Entry.NEW));
  486. }
  487. } finally {
  488. endRead();
  489. }
  490. }
  491. // Returns an input stream for reading the contents of the specified
  492. // file entry.
  493. InputStream newInputStream(byte[] path) throws IOException {
  494. beginRead();
  495. try {
  496. ensureOpen();
  497. Entry e = getEntry0(path);
  498. if (e == null)
  499. throw new NoSuchFileException(getString(path));
  500. if (e.isDir())
  501. throw new FileSystemException(getString(path), "is a directory", null);
  502. return getInputStream(e);
  503. } finally {
  504. endRead();
  505. }
  506. }
  507. private void checkOptions(Set<? extends OpenOption> options) {
  508. // check for options of null type and option is an intance of StandardOpenOption
  509. for (OpenOption option : options) {
  510. if (option == null)
  511. throw new NullPointerException();
  512. if (!(option instanceof StandardOpenOption))
  513. throw new IllegalArgumentException();
  514. }
  515. }
  516. // Returns a Writable/ReadByteChannel for now. Might consdier to use
  517. // newFileChannel() instead, which dump the entry data into a regular
  518. // file on the default file system and create a FileChannel on top of
  519. // it.
  520. SeekableByteChannel newByteChannel(byte[] path,
  521. Set<? extends OpenOption> options,
  522. FileAttribute<?>... attrs)
  523. throws IOException
  524. {
  525. checkOptions(options);
  526. if (options.contains(StandardOpenOption.WRITE) ||
  527. options.contains(StandardOpenOption.APPEND)) {
  528. checkWritable();
  529. beginRead();
  530. try {
  531. final WritableByteChannel wbc = Channels.newChannel(
  532. newOutputStream(path, options.toArray(new OpenOption[0])));
  533. long leftover = 0;
  534. if (options.contains(StandardOpenOption.APPEND)) {
  535. Entry e = getEntry0(path);
  536. if (e != null && e.size >= 0)
  537. leftover = e.size;
  538. }
  539. final long offset = leftover;
  540. return new SeekableByteChannel() {
  541. long written = offset;
  542. public boolean isOpen() {
  543. return wbc.isOpen();
  544. }
  545. public long position() throws IOException {
  546. return written;
  547. }
  548. public SeekableByteChannel position(long pos)
  549. throws IOException
  550. {
  551. throw new UnsupportedOperationException();
  552. }
  553. public int read(ByteBuffer dst) throws IOException {
  554. throw new UnsupportedOperationException();
  555. }
  556. public SeekableByteChannel truncate(long size)
  557. throws IOException
  558. {
  559. throw new UnsupportedOperationException();
  560. }
  561. public int write(ByteBuffer src) throws IOException {
  562. int n = wbc.write(src);
  563. written += n;
  564. return n;
  565. }
  566. public long size() throws IOException {
  567. return written;
  568. }
  569. public void close() throws IOException {
  570. wbc.close();
  571. }
  572. };
  573. } finally {
  574. endRead();
  575. }
  576. } else {
  577. beginRead();
  578. try {
  579. ensureOpen();
  580. Entry e = getEntry0(path);
  581. if (e == null || e.isDir())
  582. throw new NoSuchFileException(getString(path));
  583. final ReadableByteChannel rbc =
  584. Channels.newChannel(getInputStream(e));
  585. final long size = e.size;
  586. return new SeekableByteChannel() {
  587. long read = 0;
  588. public boolean isOpen() {
  589. return rbc.isOpen();
  590. }
  591. public long position() throws IOException {
  592. return read;
  593. }
  594. public SeekableByteChannel position(long pos)
  595. throws IOException
  596. {
  597. throw new UnsupportedOperationException();
  598. }
  599. public int read(ByteBuffer dst) throws IOException {
  600. return rbc.read(dst);
  601. }
  602. public SeekableByteChannel truncate(long size)
  603. throws IOException
  604. {
  605. throw new NonWritableChannelException();
  606. }
  607. public int write (ByteBuffer src) throws IOException {
  608. throw new NonWritableChannelException();
  609. }
  610. public long size() throws IOException {
  611. return size;
  612. }
  613. public void close() throws IOException {
  614. rbc.close();
  615. }
  616. };
  617. } finally {
  618. endRead();
  619. }
  620. }
  621. }
  622. // Returns a FileChannel of the specified entry.
  623. //
  624. // This implementation creates a temporary file on the default file system,
  625. // copy the entry data into it if the entry exists, and then create a
  626. // FileChannel on top of it.
  627. FileChannel newFileChannel(byte[] path,
  628. Set<? extends OpenOption> options,
  629. FileAttribute<?>... attrs)
  630. throws IOException
  631. {
  632. checkOptions(options);
  633. final boolean forWrite = (options.contains(StandardOpenOption.WRITE) ||
  634. options.contains(StandardOpenOption.APPEND));
  635. beginRead();
  636. try {
  637. ensureOpen();
  638. Entry e = getEntry0(path);
  639. if (forWrite) {
  640. checkWritable();
  641. if (e == null) {
  642. if (!options.contains(StandardOpenOption.CREATE_NEW))
  643. throw new NoSuchFileException(getString(path));
  644. } else {
  645. if (options.contains(StandardOpenOption.CREATE_NEW))
  646. throw new FileAlreadyExistsException(getString(path));
  647. if (e.isDir())
  648. throw new FileAlreadyExistsException("directory <"
  649. + getString(path) + "> exists");
  650. }
  651. options.remove(StandardOpenOption.CREATE_NEW); // for tmpfile
  652. } else if (e == null || e.isDir()) {
  653. throw new NoSuchFileException(getString(path));
  654. }
  655. final boolean isFCH = (e != null && e.type == Entry.FILECH);
  656. final Path tmpfile = isFCH ? e.file : getTempPathForEntry(path);
  657. final FileChannel fch = tmpfile.getFileSystem()
  658. .provider()
  659. .newFileChannel(tmpfile, options, attrs);
  660. final Entry u = isFCH ? e : new Entry(path, tmpfile, Entry.FILECH);
  661. if (forWrite) {
  662. u.flag = FLAG_DATADESCR;
  663. u.method = METHOD_DEFLATED;
  664. }
  665. // is there a better way to hook into the FileChannel's close method?
  666. return new FileChannel() {
  667. public int write(ByteBuffer src) throws IOException {
  668. return fch.write(src);
  669. }
  670. public long write(ByteBuffer[] srcs, int offset, int length)
  671. throws IOException
  672. {
  673. return fch.write(srcs, offset, length);
  674. }
  675. public long position() throws IOException {
  676. return fch.position();
  677. }
  678. public FileChannel position(long newPosition)
  679. throws IOException
  680. {
  681. fch.position(newPosition);
  682. return this;
  683. }
  684. public long size() throws IOException {
  685. return fch.size();
  686. }
  687. public FileChannel truncate(long size)
  688. throws IOException
  689. {
  690. fch.truncate(size);
  691. return this;
  692. }
  693. public void force(boolean metaData)
  694. throws IOException
  695. {
  696. fch.force(metaData);
  697. }
  698. public long transferTo(long position, long count,
  699. WritableByteChannel target)
  700. throws IOException
  701. {
  702. return fch.transferTo(position, count, target);
  703. }
  704. public long transferFrom(ReadableByteChannel src,
  705. long position, long count)
  706. throws IOException
  707. {
  708. return fch.transferFrom(src, position, count);
  709. }
  710. public int read(ByteBuffer dst) throws IOException {
  711. return fch.read(dst);
  712. }
  713. public int read(ByteBuffer dst, long position)
  714. throws IOException
  715. {
  716. return fch.read(dst, position);
  717. }
  718. public long read(ByteBuffer[] dsts, int offset, int length)
  719. throws IOException
  720. {
  721. return fch.read(dsts, offset, length);
  722. }
  723. public int write(ByteBuffer src, long position)
  724. throws IOException
  725. {
  726. return fch.write(src, position);
  727. }
  728. public MappedByteBuffer map(MapMode mode,
  729. long position, long size)
  730. throws IOException
  731. {
  732. throw new UnsupportedOperationException();
  733. }
  734. public FileLock lock(long position, long size, boolean shared)
  735. throws IOException
  736. {
  737. return fch.lock(position, size, shared);
  738. }
  739. public FileLock tryLock(long position, long size, boolean shared)
  740. throws IOException
  741. {
  742. return fch.tryLock(position, size, shared);
  743. }
  744. protected void implCloseChannel() throws IOException {
  745. fch.close();
  746. if (forWrite) {
  747. u.mtime = System.currentTimeMillis();
  748. u.size = Files.size(u.file);
  749. update(u);
  750. } else {
  751. if (!isFCH) // if this is a new fch for reading
  752. removeTempPathForEntry(tmpfile);
  753. }
  754. }
  755. };
  756. } finally {
  757. endRead();
  758. }
  759. }
  760. // the outstanding input streams that need to be closed
  761. private Set<InputStream> streams =
  762. Collections.synchronizedSet(new HashSet<InputStream>());
  763. // the ex-channel and ex-path that need to close when their outstanding
  764. // input streams are all closed by the obtainers.
  765. private Set<ExChannelCloser> exChClosers = new HashSet<>();
  766. private Set<Path> tmppaths = Collections.synchronizedSet(new HashSet<Path>());
  767. private Path getTempPathForEntry(byte[] path) throws IOException {
  768. Path tmpPath = createTempFileInSameDirectoryAs(zfpath);
  769. if (path != null) {
  770. Entry e = getEntry0(path);
  771. if (e != null) {
  772. try (InputStream is = newInputStream(path)) {
  773. Files.copy(is, tmpPath, REPLACE_EXISTING);
  774. }
  775. }
  776. }
  777. return tmpPath;
  778. }
  779. private void removeTempPathForEntry(Path path) throws IOException {
  780. Files.delete(path);
  781. tmppaths.remove(path);
  782. }
  783. // check if all parents really exit. ZIP spec does not require
  784. // the existence of any "parent directory".
  785. private void checkParents(byte[] path) throws IOException {
  786. beginRead();
  787. try {
  788. while ((path = getParent(path)) != null && path.length != 0) {
  789. if (!inodes.containsKey(IndexNode.keyOf(path))) {
  790. throw new NoSuchFileException(getString(path));
  791. }
  792. }
  793. } finally {
  794. endRead();
  795. }
  796. }
  797. private static byte[] ROOTPATH = new byte[0];
  798. private static byte[] getParent(byte[] path) {
  799. int off = path.length - 1;
  800. if (off > 0 && path[off] == '/') // isDirectory
  801. off--;
  802. while (off > 0 && path[off] != '/') { off--; }
  803. if (off <= 0)
  804. return ROOTPATH;
  805. return Arrays.copyOf(path, off + 1);
  806. }
  807. private final void beginWrite() {
  808. rwlock.writeLock().lock();
  809. }
  810. private final void endWrite() {
  811. rwlock.writeLock().unlock();
  812. }
  813. private final void beginRead() {
  814. rwlock.readLock().lock();
  815. }
  816. private final void endRead() {
  817. rwlock.readLock().unlock();
  818. }
  819. ///////////////////////////////////////////////////////////////////
  820. private volatile boolean isOpen = true;
  821. private final SeekableByteChannel ch; // channel to the zipfile
  822. final byte[] cen; // CEN & ENDHDR
  823. private END end;
  824. private long locpos; // position of first LOC header (usually 0)
  825. private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
  826. // name -> pos (in cen), IndexNode itself can be used as a "key"
  827. private LinkedHashMap<IndexNode, IndexNode> inodes;
  828. final byte[] getBytes(String name) {
  829. return zc.getBytes(name);
  830. }
  831. final String getString(byte[] name) {
  832. return zc.toString(name);
  833. }
  834. protected void finalize() throws IOException {
  835. close();
  836. }
  837. private long getDataPos(Entry e) throws IOException {
  838. if (e.locoff == -1) {
  839. Entry e2 = getEntry0(e.name);
  840. if (e2 == null)
  841. throw new ZipException("invalid loc for entry <" + e.name + ">");
  842. e.locoff = e2.locoff;
  843. }
  844. byte[] buf = new byte[LOCHDR];
  845. if (readFullyAt(buf, 0, buf.length, e.locoff) != buf.length)
  846. throw new ZipException("invalid loc for entry <" + e.name + ">");
  847. return locpos + e.locoff + LOCHDR + LOCNAM(buf) + LOCEXT(buf);
  848. }
  849. // Reads len bytes of data from the specified offset into buf.
  850. // Returns the total number of bytes read.
  851. // Each/every byte read from here (except the cen, which is mapped).
  852. final long readFullyAt(byte[] buf, int off, long len, long pos)
  853. throws IOException
  854. {
  855. ByteBuffer bb = ByteBuffer.wrap(buf);
  856. bb.position(off);
  857. bb.limit((int)(off + len));
  858. return readFullyAt(bb, pos);
  859. }
  860. private final long readFullyAt(ByteBuffer bb, long pos)
  861. throws IOException
  862. {
  863. synchronized(ch) {
  864. return ch.position(pos).read(bb);
  865. }
  866. }
  867. // Searches for end of central directory (END) header. The contents of
  868. // the END header will be read and placed in endbuf. Returns the file
  869. // position of the END header, otherwise returns -1 if the END header
  870. // was not found or an error occurred.
  871. private END findEND() throws IOException
  872. {
  873. byte[] buf = new byte[READBLOCKSZ];
  874. long ziplen = ch.size();
  875. long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
  876. long minPos = minHDR - (buf.length - ENDHDR);
  877. for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR))
  878. {
  879. int off = 0;
  880. if (pos < 0) {
  881. // Pretend there are some NUL bytes before start of file
  882. off = (int)-pos;
  883. Arrays.fill(buf, 0, off, (byte)0);
  884. }
  885. int len = buf.length - off;
  886. if (readFullyAt(buf, off, len, pos + off) != len)
  887. zerror("zip END header not found");
  888. // Now scan the block backwards for END header signature
  889. for (int i = buf.length - ENDHDR; i >= 0; i--) {
  890. if (buf[i+0] == (byte)'P' &&
  891. buf[i+1] == (byte)'K' &&
  892. buf[i+2] == (byte)'\005' &&
  893. buf[i+3] == (byte)'\006' &&
  894. (pos + i + ENDHDR + ENDCOM(buf, i) == ziplen)) {
  895. // Found END header
  896. buf = Arrays.copyOfRange(buf, i, i + ENDHDR);
  897. END end = new END();
  898. end.endsub = ENDSUB(buf);
  899. end.centot = ENDTOT(buf);
  900. end.cenlen = ENDSIZ(buf);
  901. end.cenoff = ENDOFF(buf);
  902. end.comlen = ENDCOM(buf);
  903. end.endpos = pos + i;
  904. if (end.cenlen == ZIP64_MINVAL ||
  905. end.cenoff == ZIP64_MINVAL ||
  906. end.centot == ZIP64_MINVAL32)
  907. {
  908. // need to find the zip64 end;
  909. byte[] loc64 = new byte[ZIP64_LOCHDR];
  910. if (readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
  911. != loc64.length) {
  912. return end;
  913. }
  914. long end64pos = ZIP64_LOCOFF(loc64);
  915. byte[] end64buf = new byte[ZIP64_ENDHDR];
  916. if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
  917. != end64buf.length) {
  918. return end;
  919. }
  920. // end64 found, re-calcualte everything.
  921. end.cenlen = ZIP64_ENDSIZ(end64buf);
  922. end.cenoff = ZIP64_ENDOFF(end64buf);
  923. end.centot = (int)ZIP64_ENDTOT(end64buf); // assume total < 2g
  924. end.endpos = end64pos;
  925. }
  926. return end;
  927. }
  928. }
  929. }
  930. zerror("zip END header not found");
  931. return null; //make compiler happy
  932. }
  933. // Reads zip file central directory. Returns the file position of first
  934. // CEN header, otherwise returns -1 if an error occured. If zip->msg != NULL
  935. // then the error was a zip format error and zip->msg has the error text.
  936. // Always pass in -1 for knownTotal; it's used for a recursive call.
  937. private byte[] initCEN() throws IOException {
  938. end = findEND();
  939. if (end.endpos == 0) {
  940. inodes = new LinkedHashMap<>(10);
  941. locpos = 0;
  942. buildNodeTree();
  943. return null; // only END header present
  944. }
  945. if (end.cenlen > end.endpos)
  946. zerror("invalid END header (bad central directory size)");
  947. long cenpos = end.endpos - end.cenlen; // position of CEN table
  948. // Get position of first local file (LOC) header, taking into
  949. // account that there may be a stub prefixed to the zip file.
  950. locpos = cenpos - end.cenoff;
  951. if (locpos < 0)
  952. zerror("invalid END header (bad central directory offset)");
  953. // read in the CEN and END
  954. byte[] cen = new byte[(int)(end.cenlen + ENDHDR)];
  955. if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
  956. zerror("read CEN tables failed");
  957. }
  958. // Iterate through the entries in the central directory
  959. inodes = new LinkedHashMap<>(end.centot + 1);
  960. int pos = 0;
  961. int limit = cen.length - ENDHDR;
  962. while (pos < limit) {
  963. if (CENSIG(cen, pos) != CENSIG)
  964. zerror("invalid CEN header (bad signature)");
  965. int method = CENHOW(cen, pos);
  966. int nlen = CENNAM(cen, pos);
  967. int elen = CENEXT(cen, pos);
  968. int clen = CENCOM(cen, pos);
  969. if ((CENFLG(cen, pos) & 1) != 0)
  970. zerror("invalid CEN header (encrypted entry)");
  971. if (method != METHOD_STORED && method != METHOD_DEFLATED)
  972. zerror("invalid CEN header (unsupported compression method: " + method + ")");
  973. if (pos + CENHDR + nlen > limit)
  974. zerror("invalid CEN header (bad header size)");
  975. byte[] name = Arrays.copyOfRange(cen, pos + CENHDR, pos + CENHDR + nlen);
  976. IndexNode inode = new IndexNode(name, pos);
  977. inodes.put(inode, inode);
  978. // skip ext and comment
  979. pos += (CENHDR + nlen + elen + clen);
  980. }
  981. if (pos + ENDHDR != cen.length) {
  982. zerror("invalid CEN header (bad header size)");
  983. }
  984. buildNodeTree();
  985. return cen;
  986. }
  987. private void ensureOpen() throws IOException {
  988. if (!isOpen)
  989. throw new ClosedFileSystemException();
  990. }
  991. // Creates a new empty temporary file in the same directory as the
  992. // specified file. A variant of File.createTempFile.
  993. private Path createTempFileInSameDirectoryAs(Path path)
  994. throws IOException
  995. {
  996. Path parent = path.toAbsolutePath().getParent();
  997. String dir = (parent == null)? "." : parent.toString();
  998. Path tmpPath = File.createTempFile("zipfstmp", null, new File(dir)).toPath();
  999. tmppaths.add(tmpPath);
  1000. return tmpPath;
  1001. }
  1002. ////////////////////update & sync //////////////////////////////////////
  1003. private boolean hasUpdate = false;
  1004. // shared key. consumer guarantees the "writeLock" before use it.
  1005. private final IndexNode LOOKUPKEY = IndexNode.keyOf(null);
  1006. private void updateDelete(IndexNode inode) {
  1007. beginWrite();
  1008. try {
  1009. removeFromTree(inode);
  1010. inodes.remove(inode);
  1011. hasUpdate = true;
  1012. } finally {
  1013. endWrite();
  1014. }
  1015. }
  1016. private void update(Entry e) {
  1017. beginWrite();
  1018. try {
  1019. IndexNode old = inodes.put(e, e);
  1020. if (old != null) {
  1021. removeFromTree(old);
  1022. }
  1023. if (e.type == Entry.NEW || e.type == Entry.FILECH) {
  1024. IndexNode parent = inodes.get(LOOKUPKEY.as(getParent(e.name)));
  1025. e.sibling = parent.child;
  1026. parent.child = e;
  1027. }
  1028. hasUpdate = true;
  1029. } finally {
  1030. endWrite();
  1031. }
  1032. }
  1033. // copy over the whole LOC entry (header if necessary, data and ext) from
  1034. // old zip to the new one.
  1035. private long copyLOCEntry(Entry e, boolean updateHeader,
  1036. OutputStream os,
  1037. long written, byte[] buf)
  1038. throws IOException
  1039. {
  1040. long locoff = e.locoff; // where to read
  1041. e.locoff = written; // update the e.locoff with new value
  1042. // calculate the size need to write out
  1043. long size = 0;
  1044. // if there is A ext
  1045. if ((e.flag & FLAG_DATADESCR) != 0) {
  1046. if (e.size >= ZIP64_MINVAL || e.csize >= ZIP64_MINVAL)
  1047. size = 24;
  1048. else
  1049. size = 16;
  1050. }
  1051. // read loc, use the original loc.elen/nlen
  1052. if (readFullyAt(buf, 0, LOCHDR , locoff) != LOCHDR)
  1053. throw new ZipException("loc: reading failed");
  1054. if (updateHeader) {
  1055. locoff += LOCHDR + LOCNAM(buf) + LOCEXT(buf); // skip header
  1056. size += e.csize;
  1057. written = e.writeLOC(os) + size;
  1058. } else {
  1059. os.write(buf, 0, LOCHDR); // write out the loc header
  1060. locoff += LOCHDR;
  1061. // use e.csize, LOCSIZ(buf) is zero if FLAG_DATADESCR is on
  1062. // size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf);
  1063. size += LOCNAM(buf) + LOCEXT(buf) + e.csize;
  1064. written = LOCHDR + size;
  1065. }
  1066. int n;
  1067. while (size > 0 &&
  1068. (n = (int)readFullyAt(buf, 0, buf.length, locoff)) != -1)
  1069. {
  1070. if (size < n)
  1071. n = (int)size;
  1072. os.write(buf, 0, n);
  1073. size -= n;
  1074. locoff += n;
  1075. }
  1076. return written;
  1077. }
  1078. // sync the zip file system, if there is any udpate
  1079. private void sync() throws IOException {
  1080. //System.out.printf("->sync(%s) starting....!%n", toString());
  1081. // check ex-closer
  1082. if (!exChClosers.isEmpty()) {
  1083. for (ExChannelCloser ecc : exChClosers) {
  1084. if (ecc.streams.isEmpty()) {
  1085. ecc.ch.close();
  1086. Files.delete(ecc.path);
  1087. exChClosers.remove(ecc);
  1088. }
  1089. }
  1090. }
  1091. if (!hasUpdate)
  1092. return;
  1093. Path tmpFile = createTempFileInSameDirectoryAs(zfpath);
  1094. try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(tmpFile, WRITE)))
  1095. {
  1096. ArrayList<Entry> elist = new ArrayList<>(inodes.size());
  1097. long written = 0;
  1098. byte[] buf = new byte[8192];
  1099. Entry e = null;
  1100. // write loc
  1101. for (IndexNode inode : inodes.values()) {
  1102. if (inode instanceof Entry) { // an updated inode
  1103. e = (Entry)inode;
  1104. try {
  1105. if (e.type == Entry.COPY) {
  1106. // entry copy: the only thing changed is the "name"
  1107. // and "nlen" in LOC header, so we udpate/rewrite the
  1108. // LOC in new file and simply copy the rest (data and
  1109. // ext) without enflating/deflating from the old zip
  1110. // file LOC entry.
  1111. written += copyLOCEntry(e, true, os, written, buf);
  1112. } else { // NEW, FILECH or CEN
  1113. e.locoff = written;
  1114. written += e.writeLOC(os); // write loc header
  1115. if (e.bytes != null) { // in-memory, deflated
  1116. os.write(e.bytes); // already
  1117. written += e.bytes.length;
  1118. } else if (e.file != null) { // tmp file
  1119. try (InputStream is = Files.newInputStream(e.file)) {
  1120. int n;
  1121. if (e.type == Entry.NEW) { // deflated already
  1122. while ((n = is.read(buf)) != -1) {
  1123. os.write(buf, 0, n);
  1124. written += n;
  1125. }
  1126. } else if (e.type == Entry.FILECH) {
  1127. // the data are not deflated, use ZEOS
  1128. try (OutputStream os2 = new EntryOutputStream(e, os)) {
  1129. while ((n = is.read(buf)) != -1) {
  1130. os2.write(buf, 0, n);
  1131. }
  1132. }
  1133. written += e.csize;
  1134. if ((e.flag & FLAG_DATADESCR) != 0)
  1135. written += e.writeEXT(os);
  1136. }
  1137. }
  1138. Files.delete(e.file);
  1139. tmppaths.remove(e.file);
  1140. } else {
  1141. // dir, 0-length data
  1142. }
  1143. }
  1144. elist.add(e);
  1145. } catch (IOException x) {
  1146. x.printStackTrace(); // skip any in-accurate entry
  1147. }
  1148. } else { // unchanged inode
  1149. if (inode.pos == -1) {
  1150. continue; // pseudo directory node
  1151. }
  1152. e = Entry.readCEN(this, inode.pos);
  1153. try {
  1154. written += copyLOCEntry(e, false, os, written, buf);
  1155. elist.add(e);
  1156. } catch (IOException x) {
  1157. x.printStackTrace(); // skip any wrong entry
  1158. }
  1159. }
  1160. }
  1161. // now write back the cen and end table
  1162. end.cenoff = written;
  1163. for (Entry entry : elist) {
  1164. written += entry.writeCEN(os);
  1165. }
  1166. end.centot = elist.size();
  1167. end.cenlen = written - end.cenoff;
  1168. end.write(os, written);
  1169. }
  1170. if (!streams.isEmpty()) {
  1171. //
  1172. // TBD: ExChannelCloser should not be necessary if we only
  1173. // sync when being closed, all streams should have been
  1174. // closed already. Keep the logic here for now.
  1175. //
  1176. // There are outstanding input streams open on existing "ch",
  1177. // so, don't close the "cha" and delete the "file for now, let
  1178. // the "ex-channel-closer" to handle them
  1179. ExChannelCloser ecc = new ExChannelCloser(
  1180. createTempFileInSameDirectoryAs(zfpath),
  1181. ch,
  1182. streams);
  1183. Files.move(zfpath, ecc.path, REPLACE_EXISTING);
  1184. exChClosers.add(ecc);
  1185. streams = Collections.synchronizedSet(new HashSet<InputStream>());
  1186. } else {
  1187. ch.close();
  1188. Files.delete(zfpath);
  1189. }
  1190. Files.move(tmpFile, zfpath, REPLACE_EXISTING);
  1191. hasUpdate = false; // clear
  1192. /*
  1193. if (isOpen) {
  1194. ch = zfpath.newByteChannel(READ); // re-fresh "ch" and "cen"
  1195. cen = initCEN();
  1196. }
  1197. */
  1198. //System.out.printf("->sync(%s) done!%n", toString());
  1199. }
  1200. private IndexNode getInode(byte[] path) {
  1201. if (path == null)
  1202. throw new NullPointerException("path");
  1203. IndexNode key = IndexNode.keyOf(path);
  1204. IndexNode inode = inodes.get(key);
  1205. if (inode == null &&
  1206. (path.length == 0 || path[path.length -1] != '/')) {
  1207. // if does not ends with a slash
  1208. path = Arrays.copyOf(path, path.length + 1);
  1209. path[path.length - 1] = '/';
  1210. inode = inodes.get(key.as(path));
  1211. }
  1212. return inode;
  1213. }
  1214. private Entry getEntry0(byte[] path) throws IOException {
  1215. IndexNode inode = getInode(path);
  1216. if (inode instanceof Entry)
  1217. return (Entry)inode;
  1218. if (inode == null || inode.pos == -1)
  1219. return null;
  1220. return Entry.readCEN(this, inode.pos);
  1221. }
  1222. public void deleteFile(byte[] path, boolean failIfNotExists)
  1223. throws IOException
  1224. {
  1225. checkWritable();
  1226. IndexNode inode = getInode(path);
  1227. if (inode == null) {
  1228. if (path != null && path.length == 0)
  1229. throw new ZipException("root directory </> can't not be delete");
  1230. if (failIfNotExists)
  1231. throw new NoSuchFileException(getString(path));
  1232. } else {
  1233. if (inode.isDir() && inode.child != null)
  1234. throw new DirectoryNotEmptyException(getString(path));
  1235. updateDelete(inode);
  1236. }
  1237. }
  1238. private static void copyStream(InputStream is, OutputStream os)
  1239. throws IOException
  1240. {
  1241. byte[] copyBuf = new byte[8192];
  1242. int n;
  1243. while ((n = is.read(copyBuf)) != -1) {
  1244. os.write(copyBuf, 0, n);
  1245. }
  1246. }
  1247. // Returns an out stream fo…

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