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.

HeaderBlock.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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.storage;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.OutputStream;
  19. import java.nio.ByteBuffer;
  20. import java.util.Arrays;
  21. import org.apache.poi.hssf.OldExcelFormatException;
  22. import org.apache.poi.poifs.common.POIFSBigBlockSize;
  23. import org.apache.poi.poifs.common.POIFSConstants;
  24. import org.apache.poi.poifs.filesystem.FileMagic;
  25. import org.apache.poi.poifs.filesystem.NotOLE2FileException;
  26. import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
  27. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  28. import org.apache.poi.util.HexDump;
  29. import org.apache.poi.util.IOUtils;
  30. import org.apache.poi.util.IntegerField;
  31. import org.apache.poi.util.LittleEndian;
  32. import org.apache.poi.util.LittleEndianConsts;
  33. import org.apache.poi.util.LongField;
  34. import org.apache.poi.util.ShortField;
  35. /**
  36. * The block containing the archive header
  37. */
  38. public final class HeaderBlock implements HeaderBlockConstants {
  39. private static final byte _default_value = ( byte ) 0xFF;
  40. /**
  41. * What big block size the file uses. Most files
  42. * use 512 bytes, but a few use 4096
  43. */
  44. private final POIFSBigBlockSize bigBlockSize;
  45. /**
  46. * Number of big block allocation table blocks (int).
  47. * (Number of FAT Sectors in Microsoft parlance).
  48. */
  49. private int _bat_count;
  50. /**
  51. * Start of the property set block (int index of the property set
  52. * chain's first big block).
  53. */
  54. private int _property_start;
  55. /**
  56. * start of the small block allocation table (int index of small
  57. * block allocation table's first big block)
  58. */
  59. private int _sbat_start;
  60. /**
  61. * Number of small block allocation table blocks (int)
  62. * (Number of MiniFAT Sectors in Microsoft parlance)
  63. */
  64. private int _sbat_count;
  65. /**
  66. * Big block index for extension to the big block allocation table
  67. */
  68. private int _xbat_start;
  69. /**
  70. * Number of big block allocation table blocks (int)
  71. * (Number of DIFAT Sectors in Microsoft parlance)
  72. */
  73. private int _xbat_count;
  74. /**
  75. * The data. Only ever 512 bytes, because 4096 byte
  76. * files use zeros for the extra header space.
  77. */
  78. private final byte[] _data;
  79. /**
  80. * create a new HeaderBlockReader from an InputStream
  81. *
  82. * @param stream the source InputStream
  83. *
  84. * @throws IOException on errors or bad data
  85. */
  86. public HeaderBlock(InputStream stream) throws IOException {
  87. // Grab the first 512 bytes
  88. // (For 4096 sized blocks, the remaining 3584 bytes are zero)
  89. // Then, process the contents
  90. this(readFirst512(stream));
  91. // Fetch the rest of the block if needed
  92. if(bigBlockSize.getBigBlockSize() != 512) {
  93. int rest = bigBlockSize.getBigBlockSize() - 512;
  94. byte[] tmp = IOUtils.safelyAllocate(rest, POIFSFileSystem.getMaxRecordLength());
  95. IOUtils.readFully(stream, tmp);
  96. }
  97. }
  98. public HeaderBlock(ByteBuffer buffer) throws IOException {
  99. this(IOUtils.toByteArray(buffer, POIFSConstants.SMALLER_BIG_BLOCK_SIZE));
  100. }
  101. private HeaderBlock(byte[] data) throws IOException {
  102. this._data = data.clone();
  103. // verify signature
  104. FileMagic fm = FileMagic.valueOf(data);
  105. switch (fm) {
  106. case OLE2:
  107. break;
  108. case OOXML:
  109. throw new OfficeXmlFileException("The supplied data appears to be in the Office 2007+ XML. "
  110. + "You are calling the part of POI that deals with OLE2 Office Documents. "
  111. + "You need to call a different part of POI to process this data (eg XSSF instead of HSSF)");
  112. case XML:
  113. throw new NotOLE2FileException("The supplied data appears to be a raw XML file. "
  114. + "Formats such as Office 2003 XML are not supported");
  115. case MSWRITE:
  116. throw new NotOLE2FileException("The supplied data appears to be in the old MS Write format. "
  117. + "Apache POI doesn't currently support this format");
  118. case WORD2:
  119. throw new NotOLE2FileException("The supplied data appears to be an old Word version 2 file. "
  120. + "Apache POI doesn't currently support this format");
  121. case BIFF2:
  122. case BIFF3:
  123. case BIFF4:
  124. throw new OldExcelFormatException("The supplied data appears to be in "+fm+" format. "
  125. + "HSSF only supports the BIFF8 format, try OldExcelExtractor");
  126. default:
  127. // Give a generic error if the OLE2 signature isn't found
  128. String exp = HexDump.longToHex(_signature);
  129. String act = HexDump.longToHex(LittleEndian.getLong(data, 0));
  130. throw new NotOLE2FileException(
  131. "Invalid header signature; read " + act + ", expected " + exp +
  132. " - Your file appears not to be a valid OLE2 document");
  133. }
  134. // Figure out our block size
  135. if (_data[30] == 12) {
  136. this.bigBlockSize = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS;
  137. } else if(_data[30] == 9) {
  138. this.bigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
  139. } else {
  140. throw new IOException("Unsupported blocksize (2^"+ _data[30] + "). Expected 2^9 or 2^12.");
  141. }
  142. // Setup the fields to read and write the counts and starts
  143. _bat_count = new IntegerField(_bat_count_offset, data).get();
  144. _property_start = new IntegerField(_property_start_offset,_data).get();
  145. _sbat_start = new IntegerField(_sbat_start_offset, _data).get();
  146. _sbat_count = new IntegerField(_sbat_block_count_offset, _data).get();
  147. _xbat_start = new IntegerField(_xbat_start_offset, _data).get();
  148. _xbat_count = new IntegerField(_xbat_count_offset, _data).get();
  149. }
  150. /**
  151. * Create a single instance initialized with default values
  152. */
  153. public HeaderBlock(POIFSBigBlockSize bigBlockSize)
  154. {
  155. this.bigBlockSize = bigBlockSize;
  156. // Our data is always 512 big no matter what
  157. _data = new byte[ POIFSConstants.SMALLER_BIG_BLOCK_SIZE ];
  158. Arrays.fill(_data, _default_value);
  159. // Set all the default values
  160. new LongField(_signature_offset, _signature, _data);
  161. new IntegerField(0x08, 0, _data);
  162. new IntegerField(0x0c, 0, _data);
  163. new IntegerField(0x10, 0, _data);
  164. new IntegerField(0x14, 0, _data);
  165. new ShortField(0x18, ( short ) 0x3b, _data);
  166. new ShortField(0x1a, ( short ) 0x3, _data);
  167. new ShortField(0x1c, ( short ) -2, _data);
  168. new ShortField(0x1e, bigBlockSize.getHeaderValue(), _data);
  169. new IntegerField(0x20, 0x6, _data);
  170. new IntegerField(0x24, 0, _data);
  171. new IntegerField(0x28, 0, _data);
  172. new IntegerField(0x34, 0, _data);
  173. new IntegerField(0x38, 0x1000, _data);
  174. // Initialize the variables
  175. _bat_count = 0;
  176. _sbat_count = 0;
  177. _xbat_count = 0;
  178. _property_start = POIFSConstants.END_OF_CHAIN;
  179. _sbat_start = POIFSConstants.END_OF_CHAIN;
  180. _xbat_start = POIFSConstants.END_OF_CHAIN;
  181. }
  182. private static byte[] readFirst512(InputStream stream) throws IOException {
  183. // Grab the first 512 bytes
  184. // (For 4096 sized blocks, the remaining 3584 bytes are zero)
  185. byte[] data = new byte[512];
  186. int bsCount = IOUtils.readFully(stream, data);
  187. if(bsCount != 512) {
  188. throw alertShortRead(bsCount);
  189. }
  190. return data;
  191. }
  192. private static IOException alertShortRead(int pRead) {
  193. int read;
  194. if (pRead < 0) {
  195. //Can't have -1 bytes read in the error message!
  196. read = 0;
  197. } else {
  198. read = pRead;
  199. }
  200. String type = " byte" + (read == 1 ? (""): ("s"));
  201. return new IOException("Unable to read entire header; "
  202. + read + type + " read; expected 512 bytes");
  203. }
  204. /**
  205. * get start of Property Table
  206. *
  207. * @return the index of the first block of the Property Table
  208. */
  209. public int getPropertyStart() {
  210. return _property_start;
  211. }
  212. /**
  213. * Set start of Property Table
  214. *
  215. * @param startBlock the index of the first block of the Property Table
  216. */
  217. public void setPropertyStart(final int startBlock) {
  218. _property_start = startBlock;
  219. }
  220. /**
  221. * @return start of small block (MiniFAT) allocation table
  222. */
  223. public int getSBATStart() {
  224. return _sbat_start;
  225. }
  226. public int getSBATCount() {
  227. return _sbat_count;
  228. }
  229. /**
  230. * Set start of small block allocation table
  231. *
  232. * @param startBlock the index of the first big block of the small
  233. * block allocation table
  234. */
  235. public void setSBATStart(final int startBlock) {
  236. _sbat_start = startBlock;
  237. }
  238. /**
  239. * Set count of SBAT blocks
  240. *
  241. * @param count the number of SBAT blocks
  242. */
  243. public void setSBATBlockCount(final int count)
  244. {
  245. _sbat_count = count;
  246. }
  247. /**
  248. * @return number of BAT blocks
  249. */
  250. public int getBATCount() {
  251. return _bat_count;
  252. }
  253. /**
  254. * Sets the number of BAT blocks that are used.
  255. * This is the number used in both the BAT and XBAT.
  256. */
  257. public void setBATCount(final int count) {
  258. _bat_count = count;
  259. }
  260. /**
  261. * Returns the offsets to the first (up to) 109
  262. * BAT sectors.
  263. * Any additional BAT sectors are held in the XBAT (DIFAT)
  264. * sectors in a chain.
  265. * @return BAT offset array
  266. */
  267. public int[] getBATArray() {
  268. // Read them in
  269. int[] result = new int[ Math.min(_bat_count,_max_bats_in_header) ];
  270. int offset = _bat_array_offset;
  271. for (int j = 0; j < result.length; j++) {
  272. result[ j ] = LittleEndian.getInt(_data, offset);
  273. offset += LittleEndianConsts.INT_SIZE;
  274. }
  275. return result;
  276. }
  277. /**
  278. * Sets the offsets of the first (up to) 109
  279. * BAT sectors.
  280. */
  281. public void setBATArray(int[] bat_array) {
  282. int count = Math.min(bat_array.length, _max_bats_in_header);
  283. int blank = _max_bats_in_header - count;
  284. int offset = _bat_array_offset;
  285. for(int i=0; i<count; i++) {
  286. LittleEndian.putInt(_data, offset, bat_array[i]);
  287. offset += LittleEndianConsts.INT_SIZE;
  288. }
  289. for(int i=0; i<blank; i++) {
  290. LittleEndian.putInt(_data, offset, POIFSConstants.UNUSED_BLOCK);
  291. offset += LittleEndianConsts.INT_SIZE;
  292. }
  293. }
  294. /**
  295. * @return XBAT (DIFAT) count
  296. */
  297. public int getXBATCount() {
  298. return _xbat_count;
  299. }
  300. /**
  301. * Sets the number of XBAT (DIFAT) blocks used
  302. */
  303. public void setXBATCount(final int count) {
  304. _xbat_count = count;
  305. }
  306. /**
  307. * @return XBAT (DIFAT) index
  308. */
  309. public int getXBATIndex() {
  310. return _xbat_start;
  311. }
  312. /**
  313. * Sets the first XBAT (DIFAT) block location
  314. */
  315. public void setXBATStart(final int startBlock) {
  316. _xbat_start = startBlock;
  317. }
  318. /**
  319. * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
  320. */
  321. public POIFSBigBlockSize getBigBlockSize() {
  322. return bigBlockSize;
  323. }
  324. /**
  325. * Write the block's data to an OutputStream
  326. *
  327. * @param stream the OutputStream to which the stored data should
  328. * be written
  329. *
  330. * @throws IOException on problems writing to the specified
  331. * stream
  332. */
  333. public void writeData(final OutputStream stream) throws IOException {
  334. // Update the counts and start positions
  335. new IntegerField(_bat_count_offset, _bat_count, _data);
  336. new IntegerField(_property_start_offset, _property_start, _data);
  337. new IntegerField(_sbat_start_offset, _sbat_start, _data);
  338. new IntegerField(_sbat_block_count_offset, _sbat_count, _data);
  339. new IntegerField(_xbat_start_offset, _xbat_start, _data);
  340. new IntegerField(_xbat_count_offset, _xbat_count, _data);
  341. // Write the main data out
  342. stream.write(_data, 0, 512);
  343. // Now do the padding if needed
  344. for(int i=POIFSConstants.SMALLER_BIG_BLOCK_SIZE; i<bigBlockSize.getBigBlockSize(); i++) {
  345. stream.write(0);
  346. }
  347. }
  348. }