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.

ChunkFactory.java 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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.hdgf.chunks;
  16. import java.io.BufferedReader;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.InputStreamReader;
  20. import java.util.ArrayList;
  21. import java.util.HashMap;
  22. import java.util.Map;
  23. import java.util.StringTokenizer;
  24. import org.apache.poi.util.IOUtils;
  25. import org.apache.poi.util.LocaleUtil;
  26. import org.apache.poi.util.POILogFactory;
  27. import org.apache.poi.util.POILogger;
  28. /**
  29. * Factor class to create the appropriate chunks, which
  30. * needs the version of the file to process the chunk header
  31. * and trailer areas.
  32. * Makes use of chunks_parse_cmds.tbl from vsdump to be able
  33. * to process the chunk value area
  34. */
  35. public final class ChunkFactory {
  36. //arbitrarily selected; may need to increase
  37. private static final int MAX_RECORD_LENGTH = 1_000_000;
  38. /** The version of the currently open document */
  39. private int version;
  40. /**
  41. * Key is a Chunk's type, value is an array of its CommandDefinitions
  42. */
  43. private final Map<Integer, CommandDefinition[]> chunkCommandDefinitions =
  44. new HashMap<>();
  45. /**
  46. * What the name is of the chunk table definitions file?
  47. * This file comes from the scratchpad resources directory.
  48. */
  49. private static final String chunkTableName =
  50. "/org/apache/poi/hdgf/chunks_parse_cmds.tbl";
  51. /** For logging problems we spot with the file */
  52. private static final POILogger logger = POILogFactory.getLogger(ChunkFactory.class);
  53. public ChunkFactory(int version) throws IOException {
  54. this.version = version;
  55. processChunkParseCommands();
  56. }
  57. /**
  58. * Open chunks_parse_cmds.tbl and process it, to get the definitions
  59. * of all the different possible chunk commands.
  60. */
  61. private void processChunkParseCommands() throws IOException {
  62. String line;
  63. InputStream cpd = null;
  64. BufferedReader inp = null;
  65. try {
  66. cpd = ChunkFactory.class.getResourceAsStream(chunkTableName);
  67. if(cpd == null) {
  68. throw new IllegalStateException("Unable to find HDGF chunk definition on the classpath - " + chunkTableName);
  69. }
  70. inp = new BufferedReader(new InputStreamReader(cpd, LocaleUtil.CHARSET_1252));
  71. while( (line = inp.readLine()) != null ) {
  72. if (line.isEmpty() || "# \t".contains(line.substring(0,1))) {
  73. continue;
  74. }
  75. // Start xxx
  76. if(!line.matches("^start [0-9]+$")) {
  77. throw new IllegalStateException("Expecting start xxx, found " + line);
  78. }
  79. int chunkType = Integer.parseInt(line.substring(6));
  80. ArrayList<CommandDefinition> defsL = new ArrayList<>();
  81. // Data entries
  82. while( (line = inp.readLine()) != null ) {
  83. if (line.startsWith("end")) {
  84. break;
  85. }
  86. StringTokenizer st = new StringTokenizer(line, " ");
  87. int defType = Integer.parseInt(st.nextToken());
  88. int offset = Integer.parseInt(st.nextToken());
  89. String name = st.nextToken("\uffff").substring(1);
  90. CommandDefinition def = new CommandDefinition(defType,offset,name);
  91. defsL.add(def);
  92. }
  93. CommandDefinition[] defs = defsL.toArray(new CommandDefinition[0]);
  94. // Add to the map
  95. chunkCommandDefinitions.put(chunkType, defs);
  96. }
  97. } finally {
  98. if (inp != null) {
  99. inp.close();
  100. }
  101. if (cpd != null) {
  102. cpd.close();
  103. }
  104. }
  105. }
  106. public int getVersion() { return version; }
  107. /**
  108. * Creates the appropriate chunk at the given location.
  109. *
  110. * @param data the chunk bytes
  111. * @param offset the offset into the chunk bytes array to start reading from
  112. *
  113. * @return the new Chunk
  114. */
  115. public Chunk createChunk(byte[] data, int offset) {
  116. // Create the header
  117. ChunkHeader header =
  118. ChunkHeader.createChunkHeader(version, data, offset);
  119. // Sanity check
  120. if(header.getLength() < 0) {
  121. throw new IllegalArgumentException("Found a chunk with a negative length, which isn't allowed");
  122. }
  123. // How far up to look
  124. int endOfDataPos = offset + header.getLength() + header.getSizeInBytes();
  125. // Check we have enough data, and tweak the header size
  126. // as required
  127. if(endOfDataPos > data.length) {
  128. logger.log(POILogger.WARN,
  129. "Header called for " + header.getLength() +" bytes, but that would take us past the end of the data!");
  130. endOfDataPos = data.length;
  131. header.setLength(data.length - offset - header.getSizeInBytes());
  132. if(header.hasTrailer()) {
  133. header.setLength(header.getLength() - 8);
  134. endOfDataPos -= 8;
  135. }
  136. if(header.hasSeparator()) {
  137. header.setLength(header.getLength() - 4);
  138. endOfDataPos -= 4;
  139. }
  140. }
  141. // Create the trailer and separator, if required
  142. ChunkTrailer trailer = null;
  143. ChunkSeparator separator = null;
  144. if(header.hasTrailer()) {
  145. if(endOfDataPos <= data.length-8) {
  146. trailer = new ChunkTrailer(
  147. data, endOfDataPos);
  148. endOfDataPos += 8;
  149. } else {
  150. logger.log(POILogger.ERROR, "Header claims a length to " + endOfDataPos + " there's then no space for the trailer in the data (" + data.length + ")");
  151. }
  152. }
  153. if(header.hasSeparator()) {
  154. if(endOfDataPos <= data.length-4) {
  155. separator = new ChunkSeparator(
  156. data, endOfDataPos);
  157. } else {
  158. logger.log(POILogger.ERROR, "Header claims a length to " + endOfDataPos + " there's then no space for the separator in the data (" + data.length + ")");
  159. }
  160. }
  161. // Now, create the chunk
  162. byte[] contents = IOUtils.safelyAllocate(header.getLength(), MAX_RECORD_LENGTH);
  163. System.arraycopy(data, offset+header.getSizeInBytes(), contents, 0, contents.length);
  164. Chunk chunk = new Chunk(header, trailer, separator, contents);
  165. // Feed in the stuff from chunks_parse_cmds.tbl
  166. CommandDefinition[] defs = chunkCommandDefinitions.get(header.getType());
  167. if (defs == null) {
  168. defs = new CommandDefinition[0];
  169. }
  170. chunk.setCommandDefinitions(defs);
  171. // Now get the chunk to process its commands
  172. chunk.processCommands();
  173. // All done
  174. return chunk;
  175. }
  176. /**
  177. * The definition of a Command, which a chunk may hold.
  178. * The Command holds the value, this describes it.
  179. */
  180. public static class CommandDefinition {
  181. private int type;
  182. private int offset;
  183. private String name;
  184. public CommandDefinition(int type, int offset, String name) {
  185. this.type = type;
  186. this.offset = offset;
  187. this.name = name;
  188. }
  189. public String getName() {
  190. return name;
  191. }
  192. public int getOffset() {
  193. return offset;
  194. }
  195. public int getType() {
  196. return type;
  197. }
  198. }
  199. }