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.

PropertyTable.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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.property;
  16. import java.io.IOException;
  17. import java.io.OutputStream;
  18. import java.nio.ByteBuffer;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.Stack;
  22. import org.apache.logging.log4j.LogManager;
  23. import org.apache.logging.log4j.Logger;
  24. import org.apache.poi.poifs.common.POIFSBigBlockSize;
  25. import org.apache.poi.poifs.common.POIFSConstants;
  26. import org.apache.poi.poifs.filesystem.BATManaged;
  27. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  28. import org.apache.poi.poifs.filesystem.POIFSStream;
  29. import org.apache.poi.poifs.storage.HeaderBlock;
  30. import org.apache.poi.util.IOUtils;
  31. import static org.apache.logging.log4j.util.Unbox.box;
  32. /**
  33. * This class embodies the Property Table for a {@link POIFSFileSystem};
  34. * this is basically the directory for all of the documents in the
  35. * filesystem and looks up entries in the filesystem to their
  36. * chain of blocks.
  37. */
  38. public final class PropertyTable implements BATManaged {
  39. private static final Logger LOG = LogManager.getLogger(PropertyTable.class);
  40. private final HeaderBlock _header_block;
  41. private final List<Property> _properties = new ArrayList<>();
  42. private final POIFSBigBlockSize _bigBigBlockSize;
  43. public PropertyTable(HeaderBlock headerBlock)
  44. {
  45. _header_block = headerBlock;
  46. _bigBigBlockSize = headerBlock.getBigBlockSize();
  47. addProperty(new RootProperty());
  48. }
  49. /**
  50. * reading constructor (used when we've read in a file and we want
  51. * to extract the property table from it). Populates the
  52. * properties thoroughly
  53. *
  54. * @param headerBlock the header block of the file
  55. * @param filesystem the filesystem to read from
  56. *
  57. * @throws IOException if anything goes wrong (which should be
  58. * a result of the input being NFG)
  59. */
  60. public PropertyTable(final HeaderBlock headerBlock, final POIFSFileSystem filesystem)
  61. throws IOException {
  62. this(
  63. headerBlock,
  64. new POIFSStream(filesystem, headerBlock.getPropertyStart())
  65. );
  66. }
  67. /* only invoked locally and from the junit tests */
  68. PropertyTable(final HeaderBlock headerBlock, final Iterable<ByteBuffer> dataSource)
  69. throws IOException {
  70. _header_block = headerBlock;
  71. _bigBigBlockSize = headerBlock.getBigBlockSize();
  72. for (ByteBuffer bb : dataSource) {
  73. // Turn it into an array
  74. byte[] data;
  75. if (bb.hasArray() && bb.arrayOffset() == 0 &&
  76. bb.array().length == _bigBigBlockSize.getBigBlockSize()) {
  77. data = bb.array();
  78. } else {
  79. data = IOUtils.safelyAllocate(_bigBigBlockSize.getBigBlockSize(), POIFSFileSystem.getMaxRecordLength());
  80. int toRead = data.length;
  81. if (bb.remaining() < _bigBigBlockSize.getBigBlockSize()) {
  82. // Looks to be a truncated block
  83. // This isn't allowed, but some third party created files
  84. // sometimes do this, and we can normally read anyway
  85. LOG.atWarn().log("Short Property Block, {} bytes instead of the expected {}", box(bb.remaining()),box(_bigBigBlockSize.getBigBlockSize()));
  86. toRead = bb.remaining();
  87. }
  88. bb.get(data, 0, toRead);
  89. }
  90. PropertyFactory.convertToProperties(data, _properties);
  91. }
  92. Property property = _properties.get(0);
  93. if (property != null) {
  94. if (property instanceof DirectoryProperty) {
  95. populatePropertyTree((DirectoryProperty) property);
  96. } else {
  97. throw new IOException("Invalid format, cannot convert property " + property + " to DirectoryProperty");
  98. }
  99. }
  100. }
  101. /**
  102. * Add a property to the list of properties we manage
  103. *
  104. * @param property the new Property to manage
  105. */
  106. public void addProperty(Property property) {
  107. _properties.add(property);
  108. }
  109. /**
  110. * Remove a property from the list of properties we manage
  111. *
  112. * @param property the Property to be removed
  113. */
  114. public void removeProperty(final Property property) {
  115. _properties.remove(property);
  116. }
  117. /**
  118. * Get the root property
  119. *
  120. * @return the root property
  121. */
  122. public RootProperty getRoot() {
  123. // it's always the first element in the List
  124. Property property = _properties.get(0);
  125. if (property instanceof RootProperty) {
  126. return (RootProperty) property;
  127. } else {
  128. throw new IllegalStateException("Invalid format, cannot convert property " +
  129. property + " to RootProperty");
  130. }
  131. }
  132. /**
  133. * Get the start block for the property table
  134. *
  135. * @return start block index
  136. */
  137. public int getStartBlock() {
  138. return _header_block.getPropertyStart();
  139. }
  140. /**
  141. * Set the start block for this instance
  142. *
  143. * @param index index into the array of BigBlock instances making
  144. * up the filesystem
  145. */
  146. public void setStartBlock(final int index) {
  147. _header_block.setPropertyStart(index);
  148. }
  149. /**
  150. * Return the number of BigBlock's this instance uses
  151. *
  152. * @return count of BigBlock instances
  153. */
  154. public int countBlocks() {
  155. long rawSize = _properties.size() * (long)POIFSConstants.PROPERTY_SIZE;
  156. int blkSize = _bigBigBlockSize.getBigBlockSize();
  157. int numBlocks = (int)(rawSize / blkSize);
  158. if ((rawSize % blkSize) != 0) {
  159. numBlocks++;
  160. }
  161. return numBlocks;
  162. }
  163. /**
  164. * Prepare to be written
  165. */
  166. public void preWrite() {
  167. List<Property> pList = new ArrayList<>();
  168. // give each property its index
  169. int i=0;
  170. for (Property p : _properties) {
  171. // only handle non-null properties
  172. if (p == null) continue;
  173. p.setIndex(i++);
  174. pList.add(p);
  175. }
  176. // prepare each property for writing
  177. for (Property p : pList) p.preWrite();
  178. }
  179. /**
  180. * Writes the properties out into the given low-level stream
  181. */
  182. public void write(POIFSStream stream) throws IOException {
  183. OutputStream os = stream.getOutputStream();
  184. for(Property property : _properties) {
  185. if(property != null) {
  186. property.writeData(os);
  187. }
  188. }
  189. os.close();
  190. // Update the start position if needed
  191. if(getStartBlock() != stream.getStartBlock()) {
  192. setStartBlock(stream.getStartBlock());
  193. }
  194. // Update the number of property blocks in the header
  195. _header_block.setPropertyCount(countBlocks());
  196. }
  197. private void populatePropertyTree(DirectoryProperty root) throws IOException {
  198. int index = root.getChildIndex();
  199. if (!Property.isValidIndex(index)) {
  200. // property has no children
  201. return;
  202. }
  203. final Stack<Property> children = new Stack<>();
  204. children.push(_properties.get(index));
  205. while (!children.empty()) {
  206. Property property = children.pop();
  207. if (property == null) {
  208. // unknown / unsupported / corrupted property, skip
  209. continue;
  210. }
  211. root.addChild(property);
  212. if (property.isDirectory()) {
  213. populatePropertyTree(( DirectoryProperty ) property);
  214. }
  215. index = property.getPreviousChildIndex();
  216. if (isValidIndex(index)) {
  217. children.push(_properties.get(index));
  218. }
  219. index = property.getNextChildIndex();
  220. if (isValidIndex(index)) {
  221. children.push(_properties.get(index));
  222. }
  223. }
  224. }
  225. private boolean isValidIndex(int index) {
  226. if (! Property.isValidIndex(index))
  227. return false;
  228. if (index < 0 || index >= _properties.size()) {
  229. LOG.atWarn().log("Property index {} outside the valid range 0..{}", box(index),box(_properties.size()));
  230. return false;
  231. }
  232. return true;
  233. }
  234. }