You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

POIFSFileSystem.java 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.filesystem;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.Closeable;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import java.nio.ByteBuffer;
  25. import java.nio.channels.Channels;
  26. import java.nio.channels.FileChannel;
  27. import java.nio.channels.ReadableByteChannel;
  28. import java.util.ArrayList;
  29. import java.util.Collections;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import org.apache.commons.math3.util.ArithmeticUtils;
  33. import org.apache.logging.log4j.LogManager;
  34. import org.apache.logging.log4j.Logger;
  35. import org.apache.poi.EmptyFileException;
  36. import org.apache.poi.poifs.common.POIFSBigBlockSize;
  37. import org.apache.poi.poifs.common.POIFSConstants;
  38. import org.apache.poi.poifs.dev.POIFSViewable;
  39. import org.apache.poi.poifs.nio.ByteArrayBackedDataSource;
  40. import org.apache.poi.poifs.nio.DataSource;
  41. import org.apache.poi.poifs.nio.FileBackedDataSource;
  42. import org.apache.poi.poifs.property.DirectoryProperty;
  43. import org.apache.poi.poifs.property.DocumentProperty;
  44. import org.apache.poi.poifs.property.PropertyTable;
  45. import org.apache.poi.poifs.storage.BATBlock;
  46. import org.apache.poi.poifs.storage.BATBlock.BATBlockAndIndex;
  47. import org.apache.poi.poifs.storage.HeaderBlock;
  48. import org.apache.poi.util.IOUtils;
  49. import org.apache.poi.util.Internal;
  50. /**
  51. * <p>This is the main class of the POIFS system; it manages the entire
  52. * life cycle of the filesystem.</p>
  53. * <p>This is the new NIO version, which uses less memory</p>
  54. */
  55. public class POIFSFileSystem extends BlockStore
  56. implements POIFSViewable, Closeable {
  57. //arbitrarily selected; may need to increase
  58. private static final int MAX_RECORD_LENGTH = 100_000;
  59. private static final Logger LOG = LogManager.getLogger(POIFSFileSystem.class);
  60. /**
  61. * Maximum number size (in blocks) of the allocation table as supported by
  62. * POI.<p>
  63. * <p>
  64. * This constant has been chosen to help POI identify corrupted data in the
  65. * header block (rather than crash immediately with {@link OutOfMemoryError}
  66. * ). It's not clear if the compound document format actually specifies any
  67. * upper limits. For files with 512 byte blocks, having an allocation table
  68. * of 65,335 blocks would correspond to a total file size of 4GB. Needless
  69. * to say, POI probably cannot handle files anywhere near that size.
  70. */
  71. private static final int MAX_BLOCK_COUNT = 65535;
  72. private POIFSMiniStore _mini_store;
  73. private PropertyTable _property_table;
  74. private final List<BATBlock> _xbat_blocks;
  75. private final List<BATBlock> _bat_blocks;
  76. private HeaderBlock _header;
  77. private DirectoryNode _root;
  78. protected DataSource _data;
  79. /**
  80. * What big block size the file uses. Most files
  81. * use 512 bytes, but a few use 4096
  82. */
  83. private POIFSBigBlockSize bigBlockSize =
  84. POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
  85. private POIFSFileSystem(boolean newFS) {
  86. _header = new HeaderBlock(bigBlockSize);
  87. _property_table = new PropertyTable(_header);
  88. _mini_store = new POIFSMiniStore(this, _property_table.getRoot(), new ArrayList<>(), _header);
  89. _xbat_blocks = new ArrayList<>();
  90. _bat_blocks = new ArrayList<>();
  91. _root = null;
  92. if (newFS) {
  93. createNewDataSource();
  94. }
  95. }
  96. protected void createNewDataSource() {
  97. // Data needs to initially hold just the header block,
  98. // a single bat block, and an empty properties section
  99. long blockSize = ArithmeticUtils.mulAndCheck(bigBlockSize.getBigBlockSize(), 3L);
  100. _data = new ByteArrayBackedDataSource(IOUtils.safelyAllocate(blockSize, MAX_RECORD_LENGTH));
  101. }
  102. /**
  103. * Constructor, intended for writing
  104. */
  105. public POIFSFileSystem() {
  106. this(true);
  107. // Reserve block 0 for the start of the Properties Table
  108. // Create a single empty BAT, at pop that at offset 1
  109. _header.setBATCount(1);
  110. _header.setBATArray(new int[]{1});
  111. BATBlock bb = BATBlock.createEmptyBATBlock(bigBlockSize, false);
  112. bb.setOurBlockIndex(1);
  113. _bat_blocks.add(bb);
  114. setNextBlock(0, POIFSConstants.END_OF_CHAIN);
  115. setNextBlock(1, POIFSConstants.FAT_SECTOR_BLOCK);
  116. _property_table.setStartBlock(0);
  117. }
  118. /**
  119. * <p>Creates a POIFSFileSystem from a <tt>File</tt>. This uses less memory than
  120. * creating from an <tt>InputStream</tt>. The File will be opened read-only</p>
  121. *
  122. * <p>Note that with this constructor, you will need to call {@link #close()}
  123. * when you're done to have the underlying file closed, as the file is
  124. * kept open during normal operation to read the data out.</p>
  125. *
  126. * @param file the File from which to read the data
  127. * @throws IOException on errors reading, or on invalid data
  128. */
  129. public POIFSFileSystem(File file)
  130. throws IOException {
  131. this(file, true);
  132. }
  133. /**
  134. * <p>Creates a POIFSFileSystem from a <tt>File</tt>. This uses less memory than
  135. * creating from an <tt>InputStream</tt>.</p>
  136. *
  137. * <p>Note that with this constructor, you will need to call {@link #close()}
  138. * when you're done to have the underlying file closed, as the file is
  139. * kept open during normal operation to read the data out.</p>
  140. *
  141. * @param file the File from which to read or read/write the data
  142. * @param readOnly whether the POIFileSystem will only be used in read-only mode
  143. * @throws IOException on errors reading, or on invalid data
  144. */
  145. public POIFSFileSystem(File file, boolean readOnly)
  146. throws IOException {
  147. this(null, file, readOnly, true);
  148. }
  149. /**
  150. * <p>Creates a POIFSFileSystem from an open <tt>FileChannel</tt>. This uses
  151. * less memory than creating from an <tt>InputStream</tt>. The stream will
  152. * be used in read-only mode.</p>
  153. *
  154. * <p>Note that with this constructor, you will need to call {@link #close()}
  155. * when you're done to have the underlying Channel closed, as the channel is
  156. * kept open during normal operation to read the data out.</p>
  157. *
  158. * @param channel the FileChannel from which to read the data
  159. * @throws IOException on errors reading, or on invalid data
  160. */
  161. public POIFSFileSystem(FileChannel channel)
  162. throws IOException {
  163. this(channel, true);
  164. }
  165. /**
  166. * <p>Creates a POIFSFileSystem from an open <tt>FileChannel</tt>. This uses
  167. * less memory than creating from an <tt>InputStream</tt>.</p>
  168. *
  169. * <p>Note that with this constructor, you will need to call {@link #close()}
  170. * when you're done to have the underlying Channel closed, as the channel is
  171. * kept open during normal operation to read the data out.</p>
  172. *
  173. * @param channel the FileChannel from which to read or read/write the data
  174. * @param readOnly whether the POIFileSystem will only be used in read-only mode
  175. * @throws IOException on errors reading, or on invalid data
  176. */
  177. public POIFSFileSystem(FileChannel channel, boolean readOnly)
  178. throws IOException {
  179. this(channel, null, readOnly, false);
  180. }
  181. @SuppressWarnings("java:S2095")
  182. private POIFSFileSystem(FileChannel channel, File srcFile, boolean readOnly, boolean closeChannelOnError)
  183. throws IOException {
  184. this(false);
  185. try {
  186. // Initialize the datasource
  187. if (srcFile != null) {
  188. if (srcFile.length() == 0)
  189. throw new EmptyFileException(srcFile);
  190. FileBackedDataSource d = new FileBackedDataSource(srcFile, readOnly);
  191. channel = d.getChannel();
  192. _data = d;
  193. } else {
  194. _data = new FileBackedDataSource(channel, readOnly);
  195. }
  196. // Get the header
  197. ByteBuffer headerBuffer = ByteBuffer.allocate(POIFSConstants.SMALLER_BIG_BLOCK_SIZE);
  198. IOUtils.readFully(channel, headerBuffer);
  199. // Have the header processed
  200. _header = new HeaderBlock(headerBuffer);
  201. // Now process the various entries
  202. readCoreContents();
  203. } catch (IOException | RuntimeException e) {
  204. // Comes from Iterators etc.
  205. // TODO Decide if we can handle these better whilst
  206. // still sticking to the iterator contract
  207. if (closeChannelOnError && channel != null) {
  208. channel.close();
  209. }
  210. throw e;
  211. }
  212. }
  213. /**
  214. * Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until
  215. * EOF. The stream is always closed.<p>
  216. * <p>
  217. * Some streams are usable after reaching EOF (typically those that return <code>true</code>
  218. * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream
  219. * <i>and</i> needs to use it after this constructor completes, a work around is to wrap the
  220. * stream in order to trap the <tt>close()</tt> call. A convenience method (
  221. * <tt>createNonClosingInputStream()</tt>) has been provided for this purpose:
  222. * <pre>
  223. * InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is);
  224. * HSSFWorkbook wb = new HSSFWorkbook(wrappedStream);
  225. * is.reset();
  226. * doSomethingElse(is);
  227. * </pre>
  228. * Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt>
  229. * method does nothing.
  230. * <pre>
  231. * ByteArrayInputStream bais = ...
  232. * HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() !
  233. * bais.reset(); // no problem
  234. * doSomethingElse(bais);
  235. * </pre>
  236. *
  237. * @param stream the InputStream from which to read the data
  238. * @throws IOException on errors reading, or on invalid data
  239. */
  240. public POIFSFileSystem(InputStream stream)
  241. throws IOException {
  242. this(false);
  243. boolean success = false;
  244. try (ReadableByteChannel channel = Channels.newChannel(stream)) {
  245. // Turn our InputStream into something NIO based
  246. // Get the header
  247. ByteBuffer headerBuffer = ByteBuffer.allocate(POIFSConstants.SMALLER_BIG_BLOCK_SIZE);
  248. IOUtils.readFully(channel, headerBuffer);
  249. // Have the header processed
  250. _header = new HeaderBlock(headerBuffer);
  251. // Sanity check the block count
  252. sanityCheckBlockCount(_header.getBATCount());
  253. // We need to buffer the whole file into memory when
  254. // working with an InputStream.
  255. // The max possible size is when each BAT block entry is used
  256. long maxSize = BATBlock.calculateMaximumSize(_header);
  257. if (maxSize > Integer.MAX_VALUE) {
  258. throw new IllegalArgumentException("Unable read a >2gb file via an InputStream");
  259. }
  260. ByteBuffer data = ByteBuffer.allocate((int) maxSize);
  261. // Copy in the header
  262. headerBuffer.position(0);
  263. data.put(headerBuffer);
  264. data.position(headerBuffer.capacity());
  265. // Now read the rest of the stream
  266. IOUtils.readFully(channel, data);
  267. success = true;
  268. // Turn it into a DataSource
  269. _data = new ByteArrayBackedDataSource(data.array(), data.position());
  270. } finally {
  271. // As per the constructor contract, always close the stream
  272. closeInputStream(stream, success);
  273. }
  274. // Now process the various entries
  275. readCoreContents();
  276. }
  277. /**
  278. * @param stream the stream to be closed
  279. * @param success <code>false</code> if an exception is currently being thrown in the calling method
  280. */
  281. private void closeInputStream(InputStream stream, boolean success) {
  282. try {
  283. stream.close();
  284. } catch (IOException e) {
  285. if (success) {
  286. throw new RuntimeException(e);
  287. }
  288. // else not success? Try block did not complete normally
  289. // just print stack trace and leave original ex to be thrown
  290. LOG.atError().withThrowable(e).log("can't close input stream");
  291. }
  292. }
  293. /**
  294. * Read and process the PropertiesTable and the
  295. * FAT / XFAT blocks, so that we're ready to
  296. * work with the file
  297. */
  298. private void readCoreContents() throws IOException {
  299. // Grab the block size
  300. bigBlockSize = _header.getBigBlockSize();
  301. // Each block should only ever be used by one of the
  302. // FAT, XFAT or Property Table. Ensure it does
  303. ChainLoopDetector loopDetector = getChainLoopDetector();
  304. // Read the FAT blocks
  305. for (int fatAt : _header.getBATArray()) {
  306. readBAT(fatAt, loopDetector);
  307. }
  308. // Work out how many FAT blocks remain in the XFATs
  309. int remainingFATs = _header.getBATCount() - _header.getBATArray().length;
  310. // Now read the XFAT blocks, and the FATs within them
  311. BATBlock xfat;
  312. int nextAt = _header.getXBATIndex();
  313. for (int i = 0; i < _header.getXBATCount(); i++) {
  314. loopDetector.claim(nextAt);
  315. ByteBuffer fatData = getBlockAt(nextAt);
  316. xfat = BATBlock.createBATBlock(bigBlockSize, fatData);
  317. xfat.setOurBlockIndex(nextAt);
  318. nextAt = xfat.getValueAt(bigBlockSize.getXBATEntriesPerBlock());
  319. _xbat_blocks.add(xfat);
  320. // Process all the (used) FATs from this XFAT
  321. int xbatFATs = Math.min(remainingFATs, bigBlockSize.getXBATEntriesPerBlock());
  322. for (int j = 0; j < xbatFATs; j++) {
  323. int fatAt = xfat.getValueAt(j);
  324. if (fatAt == POIFSConstants.UNUSED_BLOCK || fatAt == POIFSConstants.END_OF_CHAIN) break;
  325. readBAT(fatAt, loopDetector);
  326. }
  327. remainingFATs -= xbatFATs;
  328. }
  329. // We're now able to load steams
  330. // Use this to read in the properties
  331. _property_table = new PropertyTable(_header, this);
  332. // Finally read the Small Stream FAT (SBAT) blocks
  333. BATBlock sfat;
  334. List<BATBlock> sbats = new ArrayList<>();
  335. _mini_store = new POIFSMiniStore(this, _property_table.getRoot(), sbats, _header);
  336. nextAt = _header.getSBATStart();
  337. for (int i = 0; i < _header.getSBATCount() && nextAt != POIFSConstants.END_OF_CHAIN; i++) {
  338. loopDetector.claim(nextAt);
  339. ByteBuffer fatData = getBlockAt(nextAt);
  340. sfat = BATBlock.createBATBlock(bigBlockSize, fatData);
  341. sfat.setOurBlockIndex(nextAt);
  342. sbats.add(sfat);
  343. nextAt = getNextBlock(nextAt);
  344. }
  345. }
  346. private void readBAT(int batAt, ChainLoopDetector loopDetector) throws IOException {
  347. loopDetector.claim(batAt);
  348. ByteBuffer fatData = getBlockAt(batAt);
  349. BATBlock bat = BATBlock.createBATBlock(bigBlockSize, fatData);
  350. bat.setOurBlockIndex(batAt);
  351. _bat_blocks.add(bat);
  352. }
  353. private BATBlock createBAT(int offset, boolean isBAT) throws IOException {
  354. // Create a new BATBlock
  355. BATBlock newBAT = BATBlock.createEmptyBATBlock(bigBlockSize, !isBAT);
  356. newBAT.setOurBlockIndex(offset);
  357. // Ensure there's a spot in the file for it
  358. ByteBuffer buffer = ByteBuffer.allocate(bigBlockSize.getBigBlockSize());
  359. // Header isn't in BATs
  360. long writeTo = ArithmeticUtils.mulAndCheck(1L + offset, bigBlockSize.getBigBlockSize());
  361. _data.write(buffer, writeTo);
  362. // All done
  363. return newBAT;
  364. }
  365. /**
  366. * Load the block at the given offset.
  367. */
  368. @Override
  369. protected ByteBuffer getBlockAt(final int offset) throws IOException {
  370. // The header block doesn't count, so add one
  371. long blockWanted = offset + 1L;
  372. long startAt = blockWanted * bigBlockSize.getBigBlockSize();
  373. try {
  374. return _data.read(bigBlockSize.getBigBlockSize(), startAt);
  375. } catch (IndexOutOfBoundsException e) {
  376. IndexOutOfBoundsException wrapped = new IndexOutOfBoundsException("Block " + offset + " not found");
  377. wrapped.initCause(e);
  378. throw wrapped;
  379. }
  380. }
  381. /**
  382. * Load the block at the given offset,
  383. * extending the file if needed
  384. */
  385. @Override
  386. protected ByteBuffer createBlockIfNeeded(final int offset) throws IOException {
  387. try {
  388. return getBlockAt(offset);
  389. } catch (IndexOutOfBoundsException e) {
  390. // The header block doesn't count, so add one
  391. long startAt = (offset + 1L) * bigBlockSize.getBigBlockSize();
  392. // Allocate and write
  393. ByteBuffer buffer = ByteBuffer.allocate(getBigBlockSize());
  394. _data.write(buffer, startAt);
  395. // Retrieve the properly backed block
  396. return getBlockAt(offset);
  397. }
  398. }
  399. /**
  400. * Returns the BATBlock that handles the specified offset,
  401. * and the relative index within it
  402. */
  403. @Override
  404. protected BATBlockAndIndex getBATBlockAndIndex(final int offset) {
  405. return BATBlock.getBATBlockAndIndex(
  406. offset, _header, _bat_blocks
  407. );
  408. }
  409. /**
  410. * Works out what block follows the specified one.
  411. */
  412. @Override
  413. protected int getNextBlock(final int offset) {
  414. BATBlockAndIndex bai = getBATBlockAndIndex(offset);
  415. return bai.getBlock().getValueAt(bai.getIndex());
  416. }
  417. /**
  418. * Changes the record of what block follows the specified one.
  419. */
  420. @Override
  421. protected void setNextBlock(final int offset, final int nextBlock) {
  422. BATBlockAndIndex bai = getBATBlockAndIndex(offset);
  423. bai.getBlock().setValueAt(
  424. bai.getIndex(), nextBlock
  425. );
  426. }
  427. /**
  428. * Finds a free block, and returns its offset.
  429. * This method will extend the file if needed, and if doing
  430. * so, allocate new FAT blocks to address the extra space.
  431. */
  432. @Override
  433. protected int getFreeBlock() throws IOException {
  434. int numSectors = bigBlockSize.getBATEntriesPerBlock();
  435. // First up, do we have any spare ones?
  436. int offset = 0;
  437. for (BATBlock bat : _bat_blocks) {
  438. if (bat.hasFreeSectors()) {
  439. // Claim one of them and return it
  440. for (int j = 0; j < numSectors; j++) {
  441. int batValue = bat.getValueAt(j);
  442. if (batValue == POIFSConstants.UNUSED_BLOCK) {
  443. // Bingo
  444. return offset + j;
  445. }
  446. }
  447. }
  448. // Move onto the next BAT
  449. offset += numSectors;
  450. }
  451. // If we get here, then there aren't any free sectors
  452. // in any of the BATs, so we need another BAT
  453. BATBlock bat = createBAT(offset, true);
  454. bat.setValueAt(0, POIFSConstants.FAT_SECTOR_BLOCK);
  455. _bat_blocks.add(bat);
  456. // Now store a reference to the BAT in the required place
  457. if (_header.getBATCount() >= 109) {
  458. // Needs to come from an XBAT
  459. BATBlock xbat = null;
  460. for (BATBlock x : _xbat_blocks) {
  461. if (x.hasFreeSectors()) {
  462. xbat = x;
  463. break;
  464. }
  465. }
  466. if (xbat == null) {
  467. // Oh joy, we need a new XBAT too...
  468. xbat = createBAT(offset + 1, false);
  469. // Allocate our new BAT as the first block in the XBAT
  470. xbat.setValueAt(0, offset);
  471. // And allocate the XBAT in the BAT
  472. bat.setValueAt(1, POIFSConstants.DIFAT_SECTOR_BLOCK);
  473. // Will go one place higher as XBAT added in
  474. offset++;
  475. // Chain it
  476. if (_xbat_blocks.size() == 0) {
  477. _header.setXBATStart(offset);
  478. } else {
  479. _xbat_blocks.get(_xbat_blocks.size() - 1).setValueAt(
  480. bigBlockSize.getXBATEntriesPerBlock(), offset
  481. );
  482. }
  483. _xbat_blocks.add(xbat);
  484. _header.setXBATCount(_xbat_blocks.size());
  485. } else {
  486. // Allocate our BAT in the existing XBAT with space
  487. for (int i = 0; i < bigBlockSize.getXBATEntriesPerBlock(); i++) {
  488. if (xbat.getValueAt(i) == POIFSConstants.UNUSED_BLOCK) {
  489. xbat.setValueAt(i, offset);
  490. break;
  491. }
  492. }
  493. }
  494. } else {
  495. // Store us in the header
  496. int[] newBATs = new int[_header.getBATCount() + 1];
  497. System.arraycopy(_header.getBATArray(), 0, newBATs, 0, newBATs.length - 1);
  498. newBATs[newBATs.length - 1] = offset;
  499. _header.setBATArray(newBATs);
  500. }
  501. _header.setBATCount(_bat_blocks.size());
  502. // The current offset stores us, but the next one is free
  503. return offset + 1;
  504. }
  505. protected long size() throws IOException {
  506. return _data.size();
  507. }
  508. @Override
  509. protected ChainLoopDetector getChainLoopDetector() throws IOException {
  510. return new ChainLoopDetector(_data.size());
  511. }
  512. /**
  513. * For unit testing only! Returns the underlying
  514. * properties table
  515. */
  516. PropertyTable _get_property_table() {
  517. return _property_table;
  518. }
  519. /**
  520. * Returns the MiniStore, which performs a similar low
  521. * level function to this, except for the small blocks.
  522. */
  523. POIFSMiniStore getMiniStore() {
  524. return _mini_store;
  525. }
  526. /**
  527. * add a new POIFSDocument to the FileSytem
  528. *
  529. * @param document the POIFSDocument being added
  530. */
  531. void addDocument(final POIFSDocument document) {
  532. _property_table.addProperty(document.getDocumentProperty());
  533. }
  534. /**
  535. * add a new DirectoryProperty to the FileSystem
  536. *
  537. * @param directory the DirectoryProperty being added
  538. */
  539. void addDirectory(final DirectoryProperty directory) {
  540. _property_table.addProperty(directory);
  541. }
  542. /**
  543. * Create a new document to be added to the root directory
  544. *
  545. * @param stream the InputStream from which the document's data
  546. * will be obtained
  547. * @param name the name of the new POIFSDocument
  548. * @return the new DocumentEntry
  549. * @throws IOException on error creating the new POIFSDocument
  550. */
  551. public DocumentEntry createDocument(final InputStream stream,
  552. final String name)
  553. throws IOException {
  554. return getRoot().createDocument(name, stream);
  555. }
  556. /**
  557. * create a new DocumentEntry in the root entry; the data will be
  558. * provided later
  559. *
  560. * @param name the name of the new DocumentEntry
  561. * @param size the size of the new DocumentEntry
  562. * @param writer the writer of the new DocumentEntry
  563. * @return the new DocumentEntry
  564. * @throws IOException if the writer exceeds the given size
  565. */
  566. public DocumentEntry createDocument(final String name, final int size, final POIFSWriterListener writer)
  567. throws IOException {
  568. return getRoot().createDocument(name, size, writer);
  569. }
  570. /**
  571. * create a new DirectoryEntry in the root directory
  572. *
  573. * @param name the name of the new DirectoryEntry
  574. * @return the new DirectoryEntry
  575. * @throws IOException on name duplication
  576. */
  577. public DirectoryEntry createDirectory(final String name)
  578. throws IOException {
  579. return getRoot().createDirectory(name);
  580. }
  581. /**
  582. * Set the contents of a document in the root directory,
  583. * creating if needed, otherwise updating
  584. *
  585. * @param stream the InputStream from which the document's data
  586. * will be obtained
  587. * @param name the name of the new or existing POIFSDocument
  588. * @return the new or updated DocumentEntry
  589. * @throws IOException on error populating the POIFSDocument
  590. */
  591. @SuppressWarnings("UnusedReturnValue")
  592. public DocumentEntry createOrUpdateDocument(final InputStream stream, final String name)
  593. throws IOException {
  594. return getRoot().createOrUpdateDocument(name, stream);
  595. }
  596. /**
  597. * Does the filesystem support an in-place write via
  598. * {@link #writeFilesystem()} ? If false, only writing out to
  599. * a brand new file via {@link #writeFilesystem(OutputStream)}
  600. * is supported.
  601. */
  602. public boolean isInPlaceWriteable() {
  603. return (_data instanceof FileBackedDataSource) && ((FileBackedDataSource) _data).isWriteable();
  604. }
  605. /**
  606. * Write the filesystem out to the open file. Will thrown an
  607. * {@link IllegalArgumentException} if opened from an
  608. * {@link InputStream}.
  609. *
  610. * @throws IOException thrown on errors writing to the stream
  611. */
  612. public void writeFilesystem() throws IOException {
  613. if (!(_data instanceof FileBackedDataSource)) {
  614. throw new IllegalArgumentException(
  615. "POIFS opened from an inputstream, so writeFilesystem() may " +
  616. "not be called. Use writeFilesystem(OutputStream) instead"
  617. );
  618. }
  619. if (!((FileBackedDataSource) _data).isWriteable()) {
  620. throw new IllegalArgumentException(
  621. "POIFS opened in read only mode, so writeFilesystem() may " +
  622. "not be called. Open the FileSystem in read-write mode first"
  623. );
  624. }
  625. syncWithDataSource();
  626. }
  627. /**
  628. * Write the filesystem out
  629. *
  630. * @param stream the OutputStream to which the filesystem will be
  631. * written
  632. * @throws IOException thrown on errors writing to the stream
  633. */
  634. public void writeFilesystem(final OutputStream stream) throws IOException {
  635. // Have the datasource updated
  636. syncWithDataSource();
  637. // Now copy the contents to the stream
  638. _data.copyTo(stream);
  639. }
  640. /**
  641. * Has our in-memory objects write their state
  642. * to their backing blocks
  643. */
  644. private void syncWithDataSource() throws IOException {
  645. // Mini Stream + SBATs first, as mini-stream details have
  646. // to be stored in the Root Property
  647. _mini_store.syncWithDataSource();
  648. // Properties
  649. POIFSStream propStream = new POIFSStream(this, _header.getPropertyStart());
  650. _property_table.preWrite();
  651. _property_table.write(propStream);
  652. // _header.setPropertyStart has been updated on write ...
  653. // HeaderBlock
  654. ByteArrayOutputStream baos = new ByteArrayOutputStream(
  655. _header.getBigBlockSize().getBigBlockSize()
  656. );
  657. _header.writeData(baos);
  658. getBlockAt(-1).put(baos.toByteArray());
  659. // BATs
  660. for (BATBlock bat : _bat_blocks) {
  661. ByteBuffer block = getBlockAt(bat.getOurBlockIndex());
  662. bat.writeData(block);
  663. }
  664. // XBats
  665. for (BATBlock bat : _xbat_blocks) {
  666. ByteBuffer block = getBlockAt(bat.getOurBlockIndex());
  667. bat.writeData(block);
  668. }
  669. }
  670. /**
  671. * Closes the FileSystem, freeing any underlying files, streams
  672. * and buffers. After this, you will be unable to read or
  673. * write from the FileSystem.
  674. */
  675. @Override
  676. public void close() throws IOException {
  677. _data.close();
  678. }
  679. /**
  680. * read in a file and write it back out again
  681. *
  682. * @param args names of the files; arg[ 0 ] is the input file,
  683. * arg[ 1 ] is the output file
  684. */
  685. public static void main(String[] args) throws IOException {
  686. if (args.length != 2) {
  687. System.err.println(
  688. "two arguments required: input filename and output filename");
  689. System.exit(1);
  690. }
  691. try (FileInputStream istream = new FileInputStream(args[0])) {
  692. try (FileOutputStream ostream = new FileOutputStream(args[1])) {
  693. try (POIFSFileSystem fs = new POIFSFileSystem(istream)) {
  694. fs.writeFilesystem(ostream);
  695. }
  696. }
  697. }
  698. }
  699. /**
  700. * Get the root entry
  701. *
  702. * @return the root entry
  703. */
  704. public DirectoryNode getRoot() {
  705. if (_root == null) {
  706. _root = new DirectoryNode(_property_table.getRoot(), this, null);
  707. }
  708. return _root;
  709. }
  710. /**
  711. * open a document in the root entry's list of entries
  712. *
  713. * @param documentName the name of the document to be opened
  714. * @return a newly opened DocumentInputStream
  715. * @throws IOException if the document does not exist or the
  716. * name is that of a DirectoryEntry
  717. */
  718. public DocumentInputStream createDocumentInputStream(
  719. final String documentName) throws IOException {
  720. return getRoot().createDocumentInputStream(documentName);
  721. }
  722. /**
  723. * remove an entry
  724. *
  725. * @param entry to be removed
  726. */
  727. void remove(EntryNode entry) throws IOException {
  728. // If it's a document, free the blocks
  729. if (entry instanceof DocumentEntry) {
  730. POIFSDocument doc = new POIFSDocument((DocumentProperty) entry.getProperty(), this);
  731. doc.free();
  732. }
  733. // Now zap it from the properties list
  734. _property_table.removeProperty(entry.getProperty());
  735. }
  736. /* ********** START begin implementation of POIFSViewable ********** */
  737. /**
  738. * Get an array of objects, some of which may implement
  739. * POIFSViewable
  740. *
  741. * @return an array of Object; may not be null, but may be empty
  742. */
  743. @Override
  744. public Object[] getViewableArray() {
  745. if (preferArray()) {
  746. return getRoot().getViewableArray();
  747. }
  748. return new Object[0];
  749. }
  750. /**
  751. * Get an Iterator of objects, some of which may implement
  752. * POIFSViewable
  753. *
  754. * @return an Iterator; may not be null, but may have an empty
  755. * back end store
  756. */
  757. @Override
  758. public Iterator<Object> getViewableIterator() {
  759. if (!preferArray()) {
  760. return getRoot().getViewableIterator();
  761. }
  762. return Collections.emptyIterator();
  763. }
  764. /**
  765. * Give viewers a hint as to whether to call getViewableArray or
  766. * getViewableIterator
  767. *
  768. * @return true if a viewer should call getViewableArray, false if
  769. * a viewer should call getViewableIterator
  770. */
  771. @Override
  772. public boolean preferArray() {
  773. return getRoot().preferArray();
  774. }
  775. /**
  776. * Provides a short description of the object, to be used when a
  777. * POIFSViewable object has not provided its contents.
  778. *
  779. * @return short description
  780. */
  781. @Override
  782. public String getShortDescription() {
  783. return "POIFS FileSystem";
  784. }
  785. /* ********** END begin implementation of POIFSViewable ********** */
  786. /**
  787. * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
  788. */
  789. public int getBigBlockSize() {
  790. return bigBlockSize.getBigBlockSize();
  791. }
  792. /**
  793. * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
  794. */
  795. @SuppressWarnings("WeakerAccess")
  796. public POIFSBigBlockSize getBigBlockSizeDetails() {
  797. return bigBlockSize;
  798. }
  799. /**
  800. * Creates a new {@link POIFSFileSystem} in a new {@link File}.
  801. * Use {@link #POIFSFileSystem(File)} to open an existing File,
  802. * this should only be used to create a new empty filesystem.
  803. *
  804. * @param file The file to create and open
  805. * @return The created and opened {@link POIFSFileSystem}
  806. */
  807. public static POIFSFileSystem create(File file) throws IOException {
  808. // Create a new empty POIFS in the file
  809. try (POIFSFileSystem tmp = new POIFSFileSystem();
  810. OutputStream out = new FileOutputStream(file)) {
  811. tmp.writeFilesystem(out);
  812. }
  813. // Open it up again backed by the file
  814. return new POIFSFileSystem(file, false);
  815. }
  816. @Override
  817. protected int getBlockStoreBlockSize() {
  818. return getBigBlockSize();
  819. }
  820. @Internal
  821. public PropertyTable getPropertyTable() {
  822. return _property_table;
  823. }
  824. @Internal
  825. public HeaderBlock getHeaderBlock() {
  826. return _header;
  827. }
  828. @Override
  829. protected void releaseBuffer(ByteBuffer buffer) {
  830. if (_data instanceof FileBackedDataSource) {
  831. ((FileBackedDataSource)_data).releaseBuffer(buffer);
  832. }
  833. }
  834. private static void sanityCheckBlockCount(int block_count) throws IOException {
  835. if (block_count <= 0) {
  836. throw new IOException(
  837. "Illegal block count; minimum count is 1, got " +
  838. block_count + " instead"
  839. );
  840. }
  841. if (block_count > MAX_BLOCK_COUNT) {
  842. throw new IOException(
  843. "Block count " + block_count +
  844. " is too high. POI maximum is " + MAX_BLOCK_COUNT + "."
  845. );
  846. }
  847. }
  848. }