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.

VBAMacroReader.java 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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.macros;
  16. import static org.apache.logging.log4j.util.Unbox.box;
  17. import static org.apache.poi.util.StringUtil.endsWithIgnoreCase;
  18. import static org.apache.poi.util.StringUtil.startsWithIgnoreCase;
  19. import java.io.ByteArrayInputStream;
  20. import java.io.ByteArrayOutputStream;
  21. import java.io.Closeable;
  22. import java.io.EOFException;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.InputStreamReader;
  28. import java.nio.charset.Charset;
  29. import java.nio.charset.StandardCharsets;
  30. import java.util.HashMap;
  31. import java.util.LinkedHashMap;
  32. import java.util.Map;
  33. import java.util.zip.ZipEntry;
  34. import java.util.zip.ZipInputStream;
  35. import org.apache.logging.log4j.LogManager;
  36. import org.apache.logging.log4j.Logger;
  37. import org.apache.poi.poifs.filesystem.DirectoryNode;
  38. import org.apache.poi.poifs.filesystem.DocumentInputStream;
  39. import org.apache.poi.poifs.filesystem.DocumentNode;
  40. import org.apache.poi.poifs.filesystem.Entry;
  41. import org.apache.poi.poifs.filesystem.FileMagic;
  42. import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
  43. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  44. import org.apache.poi.poifs.macros.Module.ModuleType;
  45. import org.apache.poi.util.CodePageUtil;
  46. import org.apache.poi.util.HexDump;
  47. import org.apache.poi.util.IOUtils;
  48. import org.apache.poi.util.LittleEndian;
  49. import org.apache.poi.util.RLEDecompressingInputStream;
  50. import org.apache.poi.util.StringUtil;
  51. /**
  52. * <p>Finds all VBA Macros in an office file (OLE2/POIFS and OOXML/OPC),
  53. * and returns them.
  54. * </p>
  55. * <p>
  56. * <b>NOTE:</b> This does not read macros from .ppt files.
  57. * See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF() in the scratchpad
  58. * module for an example of how to do this. Patches that make macro
  59. * extraction from .ppt more elegant are welcomed!
  60. * </p>
  61. *
  62. * @since 3.15-beta2
  63. */
  64. public class VBAMacroReader implements Closeable {
  65. private static final Logger LOGGER = LogManager.getLogger(VBAMacroReader.class);
  66. //arbitrary limit on size of strings to read, etc.
  67. private static final int MAX_STRING_LENGTH = 20000;
  68. protected static final String VBA_PROJECT_OOXML = "vbaProject.bin";
  69. protected static final String VBA_PROJECT_POIFS = "VBA";
  70. private POIFSFileSystem fs;
  71. public VBAMacroReader(InputStream rstream) throws IOException {
  72. InputStream is = FileMagic.prepareToCheckMagic(rstream);
  73. FileMagic fm = FileMagic.valueOf(is);
  74. if (fm == FileMagic.OLE2) {
  75. fs = new POIFSFileSystem(is);
  76. } else {
  77. openOOXML(is);
  78. }
  79. }
  80. public VBAMacroReader(File file) throws IOException {
  81. try {
  82. this.fs = new POIFSFileSystem(file);
  83. } catch (OfficeXmlFileException e) {
  84. openOOXML(new FileInputStream(file));
  85. }
  86. }
  87. public VBAMacroReader(POIFSFileSystem fs) {
  88. this.fs = fs;
  89. }
  90. private void openOOXML(InputStream zipFile) throws IOException {
  91. try(ZipInputStream zis = new ZipInputStream(zipFile)) {
  92. ZipEntry zipEntry;
  93. while ((zipEntry = zis.getNextEntry()) != null) {
  94. if (endsWithIgnoreCase(zipEntry.getName(), VBA_PROJECT_OOXML)) {
  95. try {
  96. // Make a POIFSFileSystem from the contents, and close the stream
  97. this.fs = new POIFSFileSystem(zis);
  98. return;
  99. } catch (IOException e) {
  100. // Tidy up
  101. zis.close();
  102. // Pass on
  103. throw e;
  104. }
  105. }
  106. }
  107. }
  108. throw new IllegalArgumentException("No VBA project found");
  109. }
  110. public void close() throws IOException {
  111. fs.close();
  112. fs = null;
  113. }
  114. public Map<String, Module> readMacroModules() throws IOException {
  115. final ModuleMap modules = new ModuleMap();
  116. //ascii -> unicode mapping for module names
  117. //preserve insertion order
  118. final Map<String, String> moduleNameMap = new LinkedHashMap<>();
  119. findMacros(fs.getRoot(), modules);
  120. findModuleNameMap(fs.getRoot(), moduleNameMap, modules);
  121. findProjectProperties(fs.getRoot(), moduleNameMap, modules);
  122. Map<String, Module> moduleSources = new HashMap<>();
  123. for (Map.Entry<String, ModuleImpl> entry : modules.entrySet()) {
  124. ModuleImpl module = entry.getValue();
  125. module.charset = modules.charset;
  126. moduleSources.put(entry.getKey(), module);
  127. }
  128. return moduleSources;
  129. }
  130. /**
  131. * Reads all macros from all modules of the opened office file.
  132. * @return All the macros and their contents
  133. *
  134. * @since 3.15-beta2
  135. */
  136. public Map<String, String> readMacros() throws IOException {
  137. Map<String, Module> modules = readMacroModules();
  138. Map<String, String> moduleSources = new HashMap<>();
  139. for (Map.Entry<String, Module> entry : modules.entrySet()) {
  140. moduleSources.put(entry.getKey(), entry.getValue().getContent());
  141. }
  142. return moduleSources;
  143. }
  144. protected static class ModuleImpl implements Module {
  145. Integer offset;
  146. byte[] buf;
  147. ModuleType moduleType;
  148. Charset charset;
  149. void read(InputStream in) throws IOException {
  150. final ByteArrayOutputStream out = new ByteArrayOutputStream();
  151. IOUtils.copy(in, out);
  152. out.close();
  153. buf = out.toByteArray();
  154. }
  155. public String getContent() {
  156. return new String(buf, charset);
  157. }
  158. public ModuleType geModuleType() {
  159. return moduleType;
  160. }
  161. }
  162. protected static class ModuleMap extends HashMap<String, ModuleImpl> {
  163. Charset charset = StringUtil.WIN_1252; // default charset
  164. }
  165. /**
  166. * Recursively traverses directory structure rooted at <tt>dir</tt>.
  167. * For each macro module that is found, the module's name and code are
  168. * added to <tt>modules<tt>.
  169. *
  170. * @param dir The directory of entries to look at
  171. * @param modules The resulting map of modules
  172. * @throws IOException If reading the VBA module fails
  173. * @since 3.15-beta2
  174. */
  175. protected void findMacros(DirectoryNode dir, ModuleMap modules) throws IOException {
  176. if (VBA_PROJECT_POIFS.equalsIgnoreCase(dir.getName())) {
  177. // VBA project directory, process
  178. readMacros(dir, modules);
  179. } else {
  180. // Check children
  181. for (Entry child : dir) {
  182. if (child instanceof DirectoryNode) {
  183. findMacros((DirectoryNode)child, modules);
  184. }
  185. }
  186. }
  187. }
  188. /**
  189. * reads module from DIR node in input stream and adds it to the modules map for decompression later
  190. * on the second pass through this function, the module will be decompressed
  191. *
  192. * Side-effects: adds a new module to the module map or sets the buf field on the module
  193. * to the decompressed stream contents (the VBA code for one module)
  194. *
  195. * @param in the run-length encoded input stream to read from
  196. * @param streamName the stream name of the module
  197. * @param modules a map to store the modules
  198. * @throws IOException If reading data from the stream or from modules fails
  199. */
  200. private static void readModuleMetadataFromDirStream(RLEDecompressingInputStream in, String streamName, ModuleMap modules) throws IOException {
  201. int moduleOffset = in.readInt();
  202. ModuleImpl module = modules.get(streamName);
  203. if (module == null) {
  204. // First time we've seen the module. Add it to the ModuleMap and decompress it later
  205. module = new ModuleImpl();
  206. module.offset = moduleOffset;
  207. modules.put(streamName, module);
  208. // Would adding module.read(in) here be correct?
  209. } else {
  210. // Decompress a previously found module and store the decompressed result into module.buf
  211. InputStream stream = new RLEDecompressingInputStream(
  212. new ByteArrayInputStream(module.buf, moduleOffset, module.buf.length - moduleOffset)
  213. );
  214. module.read(stream);
  215. stream.close();
  216. }
  217. }
  218. private static void readModuleFromDocumentStream(DocumentNode documentNode, String name, ModuleMap modules) throws IOException {
  219. ModuleImpl module = modules.get(name);
  220. // TODO Refactor this to fetch dir then do the rest
  221. if (module == null) {
  222. // no DIR stream with offsets yet, so store the compressed bytes for later
  223. module = new ModuleImpl();
  224. modules.put(name, module);
  225. try (InputStream dis = new DocumentInputStream(documentNode)) {
  226. module.read(dis);
  227. }
  228. } else if (module.buf == null) { //if we haven't already read the bytes for the module keyed off this name...
  229. if (module.offset == null) {
  230. //This should not happen. bug 59858
  231. throw new IOException("Module offset for '" + name + "' was never read.");
  232. }
  233. //try the general case, where module.offset is accurate
  234. try (InputStream compressed = new DocumentInputStream(documentNode)) {
  235. // we know the offset already, so decompress immediately on-the-fly
  236. trySkip(compressed, module.offset);
  237. try (InputStream decompressed = new RLEDecompressingInputStream(compressed)) {
  238. module.read(decompressed);
  239. }
  240. return;
  241. } catch (IllegalArgumentException | IllegalStateException e) {
  242. }
  243. //bad module.offset, try brute force
  244. ;
  245. byte[] decompressedBytes;
  246. try (InputStream compressed = new DocumentInputStream(documentNode)) {
  247. decompressedBytes = findCompressedStreamWBruteForce(compressed);
  248. }
  249. if (decompressedBytes != null) {
  250. module.read(new ByteArrayInputStream(decompressedBytes));
  251. }
  252. }
  253. }
  254. /**
  255. * Skips <tt>n</tt> bytes in an input stream, throwing IOException if the
  256. * number of bytes skipped is different than requested.
  257. * @throws IOException If skipping would exceed the available data or skipping did not work.
  258. */
  259. private static void trySkip(InputStream in, long n) throws IOException {
  260. long skippedBytes = IOUtils.skipFully(in, n);
  261. if (skippedBytes != n) {
  262. if (skippedBytes < 0) {
  263. throw new IOException(
  264. "Tried skipping " + n + " bytes, but no bytes were skipped. "
  265. + "The end of the stream has been reached or the stream is closed.");
  266. } else {
  267. throw new IOException(
  268. "Tried skipping " + n + " bytes, but only " + skippedBytes + " bytes were skipped. "
  269. + "This should never happen with a non-corrupt file.");
  270. }
  271. }
  272. }
  273. // Constants from MS-OVBA: https://msdn.microsoft.com/en-us/library/office/cc313094(v=office.12).aspx
  274. private static final int STREAMNAME_RESERVED = 0x0032;
  275. private static final int PROJECT_CONSTANTS_RESERVED = 0x003C;
  276. private static final int HELP_FILE_PATH_RESERVED = 0x003D;
  277. private static final int REFERENCE_NAME_RESERVED = 0x003E;
  278. private static final int DOC_STRING_RESERVED = 0x0040;
  279. private static final int MODULE_DOCSTRING_RESERVED = 0x0048;
  280. /**
  281. * Reads VBA Project modules from a VBA Project directory located at
  282. * <tt>macroDir</tt> into <tt>modules</tt>.
  283. *
  284. * @since 3.15-beta2
  285. */
  286. protected void readMacros(DirectoryNode macroDir, ModuleMap modules) throws IOException {
  287. //bug59858 shows that dirstream may not be in this directory (\MBD00082648\_VBA_PROJECT_CUR\VBA ENTRY NAME)
  288. //but may be in another directory (\_VBA_PROJECT_CUR\VBA ENTRY NAME)
  289. //process the dirstream first -- "dir" is case insensitive
  290. for (String entryName : macroDir.getEntryNames()) {
  291. if ("dir".equalsIgnoreCase(entryName)) {
  292. processDirStream(macroDir.getEntry(entryName), modules);
  293. break;
  294. }
  295. }
  296. for (Entry entry : macroDir) {
  297. if (! (entry instanceof DocumentNode)) { continue; }
  298. String name = entry.getName();
  299. DocumentNode document = (DocumentNode)entry;
  300. if (! "dir".equalsIgnoreCase(name) && !startsWithIgnoreCase(name, "__SRP")
  301. && !startsWithIgnoreCase(name, "_VBA_PROJECT")) {
  302. // process module, skip __SRP and _VBA_PROJECT since these do not contain macros
  303. readModuleFromDocumentStream(document, name, modules);
  304. }
  305. }
  306. }
  307. protected void findProjectProperties(DirectoryNode node, Map<String, String> moduleNameMap, ModuleMap modules) throws IOException {
  308. for (Entry entry : node) {
  309. if ("project".equalsIgnoreCase(entry.getName())) {
  310. DocumentNode document = (DocumentNode)entry;
  311. try(DocumentInputStream dis = new DocumentInputStream(document)) {
  312. readProjectProperties(dis, moduleNameMap, modules);
  313. return;
  314. }
  315. } else if (entry instanceof DirectoryNode) {
  316. findProjectProperties((DirectoryNode)entry, moduleNameMap, modules);
  317. }
  318. }
  319. }
  320. protected void findModuleNameMap(DirectoryNode node, Map<String, String> moduleNameMap, ModuleMap modules) throws IOException {
  321. for (Entry entry : node) {
  322. if ("projectwm".equalsIgnoreCase(entry.getName())) {
  323. DocumentNode document = (DocumentNode)entry;
  324. try(DocumentInputStream dis = new DocumentInputStream(document)) {
  325. readNameMapRecords(dis, moduleNameMap, modules.charset);
  326. return;
  327. }
  328. } else if (entry.isDirectoryEntry()) {
  329. findModuleNameMap((DirectoryNode)entry, moduleNameMap, modules);
  330. }
  331. }
  332. }
  333. private enum RecordType {
  334. // Constants from MS-OVBA: https://msdn.microsoft.com/en-us/library/office/cc313094(v=office.12).aspx
  335. MODULE_OFFSET(0x0031),
  336. PROJECT_SYS_KIND(0x01),
  337. PROJECT_LCID(0x0002),
  338. PROJECT_LCID_INVOKE(0x14),
  339. PROJECT_CODEPAGE(0x0003),
  340. PROJECT_NAME(0x04),
  341. PROJECT_DOC_STRING(0x05),
  342. PROJECT_HELP_FILE_PATH(0x06),
  343. PROJECT_HELP_CONTEXT(0x07, 8),
  344. PROJECT_LIB_FLAGS(0x08),
  345. PROJECT_VERSION(0x09, 10),
  346. PROJECT_CONSTANTS(0x0C),
  347. PROJECT_MODULES(0x0F),
  348. DIR_STREAM_TERMINATOR(0x10),
  349. PROJECT_COOKIE(0x13),
  350. MODULE_NAME(0x19),
  351. MODULE_NAME_UNICODE(0x47),
  352. MODULE_STREAM_NAME(0x1A),
  353. MODULE_DOC_STRING(0x1C),
  354. MODULE_HELP_CONTEXT(0x1E),
  355. MODULE_COOKIE(0x2c),
  356. MODULE_TYPE_PROCEDURAL(0x21, 4),
  357. MODULE_TYPE_OTHER(0x22, 4),
  358. MODULE_PRIVATE(0x28, 4),
  359. REFERENCE_NAME(0x16),
  360. REFERENCE_REGISTERED(0x0D),
  361. REFERENCE_PROJECT(0x0E),
  362. REFERENCE_CONTROL_A(0x2F),
  363. //according to the spec, REFERENCE_CONTROL_B(0x33) should have the
  364. //same structure as REFERENCE_CONTROL_A(0x2F).
  365. //However, it seems to have the int(length) record structure that most others do.
  366. //See 59830.xls for this record.
  367. REFERENCE_CONTROL_B(0x33),
  368. //REFERENCE_ORIGINAL(0x33),
  369. MODULE_TERMINATOR(0x002B),
  370. EOF(-1),
  371. UNKNOWN(-2);
  372. private final int VARIABLE_LENGTH = -1;
  373. private final int id;
  374. private final int constantLength;
  375. RecordType(int id) {
  376. this.id = id;
  377. this.constantLength = VARIABLE_LENGTH;
  378. }
  379. RecordType(int id, int constantLength) {
  380. this.id = id;
  381. this.constantLength = constantLength;
  382. }
  383. int getConstantLength() {
  384. return constantLength;
  385. }
  386. static RecordType lookup(int id) {
  387. for (RecordType type : RecordType.values()) {
  388. if (type.id == id) {
  389. return type;
  390. }
  391. }
  392. return UNKNOWN;
  393. }
  394. }
  395. private enum DIR_STATE {
  396. INFORMATION_RECORD,
  397. REFERENCES_RECORD,
  398. MODULES_RECORD
  399. }
  400. private static class ASCIIUnicodeStringPair {
  401. private final String ascii;
  402. private final String unicode;
  403. private final int pushbackRecordId;
  404. ASCIIUnicodeStringPair(String ascii, int pushbackRecordId) {
  405. this.ascii = ascii;
  406. this.unicode = "";
  407. this.pushbackRecordId = pushbackRecordId;
  408. }
  409. ASCIIUnicodeStringPair(String ascii, String unicode) {
  410. this.ascii = ascii;
  411. this.unicode = unicode;
  412. pushbackRecordId = -1;
  413. }
  414. private String getAscii() {
  415. return ascii;
  416. }
  417. private String getUnicode() {
  418. return unicode;
  419. }
  420. private int getPushbackRecordId() {
  421. return pushbackRecordId;
  422. }
  423. }
  424. private void processDirStream(Entry dir, ModuleMap modules) throws IOException {
  425. DocumentNode dirDocumentNode = (DocumentNode)dir;
  426. DIR_STATE dirState = DIR_STATE.INFORMATION_RECORD;
  427. try (DocumentInputStream dis = new DocumentInputStream(dirDocumentNode)) {
  428. String streamName = null;
  429. int recordId = 0;
  430. try (RLEDecompressingInputStream in = new RLEDecompressingInputStream(dis)) {
  431. while (true) {
  432. recordId = in.readShort();
  433. if (recordId == -1) {
  434. break;
  435. }
  436. RecordType type = RecordType.lookup(recordId);
  437. if (type.equals(RecordType.EOF) || type.equals(RecordType.DIR_STREAM_TERMINATOR)) {
  438. break;
  439. }
  440. switch (type) {
  441. case PROJECT_VERSION:
  442. trySkip(in, RecordType.PROJECT_VERSION.getConstantLength());
  443. break;
  444. case PROJECT_CODEPAGE:
  445. in.readInt();//record size must == 4
  446. int codepage = in.readShort();
  447. modules.charset = Charset.forName(CodePageUtil.codepageToEncoding(codepage, true));
  448. break;
  449. case MODULE_STREAM_NAME:
  450. ASCIIUnicodeStringPair pair = readStringPair(in, modules.charset, STREAMNAME_RESERVED);
  451. streamName = pair.getAscii();
  452. break;
  453. case PROJECT_DOC_STRING:
  454. readStringPair(in, modules.charset, DOC_STRING_RESERVED);
  455. break;
  456. case PROJECT_HELP_FILE_PATH:
  457. readStringPair(in, modules.charset, HELP_FILE_PATH_RESERVED);
  458. break;
  459. case PROJECT_CONSTANTS:
  460. readStringPair(in, modules.charset, PROJECT_CONSTANTS_RESERVED);
  461. break;
  462. case REFERENCE_NAME:
  463. if (dirState.equals(DIR_STATE.INFORMATION_RECORD)) {
  464. dirState = DIR_STATE.REFERENCES_RECORD;
  465. }
  466. ASCIIUnicodeStringPair stringPair = readStringPair(in,
  467. modules.charset, REFERENCE_NAME_RESERVED, false);
  468. if (stringPair.getPushbackRecordId() == -1) {
  469. break;
  470. }
  471. //Special handling for when there's only an ascii string and a REFERENCED_REGISTERED
  472. //record that follows.
  473. //See https://github.com/decalage2/oletools/blob/master/oletools/olevba.py#L1516
  474. //and https://github.com/decalage2/oletools/pull/135 from (@c1fe)
  475. if (stringPair.getPushbackRecordId() != RecordType.REFERENCE_REGISTERED.id) {
  476. throw new IllegalArgumentException("Unexpected reserved character. "+
  477. "Expected "+Integer.toHexString(REFERENCE_NAME_RESERVED)
  478. + " or "+Integer.toHexString(RecordType.REFERENCE_REGISTERED.id)+
  479. " not: "+Integer.toHexString(stringPair.getPushbackRecordId()));
  480. }
  481. //fall through!
  482. case REFERENCE_REGISTERED:
  483. //REFERENCE_REGISTERED must come immediately after
  484. //REFERENCE_NAME to allow for fall through in special case of bug 62625
  485. int recLength = in.readInt();
  486. trySkip(in, recLength);
  487. break;
  488. case MODULE_DOC_STRING:
  489. int modDocStringLength = in.readInt();
  490. readString(in, modDocStringLength, modules.charset);
  491. int modDocStringReserved = in.readShort();
  492. if (modDocStringReserved != MODULE_DOCSTRING_RESERVED) {
  493. throw new IOException("Expected x003C after stream name before Unicode stream name, but found: " +
  494. Integer.toHexString(modDocStringReserved));
  495. }
  496. int unicodeModDocStringLength = in.readInt();
  497. readUnicodeString(in, unicodeModDocStringLength);
  498. // do something with this at some point
  499. break;
  500. case MODULE_OFFSET:
  501. int modOffsetSz = in.readInt();
  502. //should be 4
  503. readModuleMetadataFromDirStream(in, streamName, modules);
  504. break;
  505. case PROJECT_MODULES:
  506. dirState = DIR_STATE.MODULES_RECORD;
  507. in.readInt();//size must == 2
  508. in.readShort();//number of modules
  509. break;
  510. case REFERENCE_CONTROL_A:
  511. int szTwiddled = in.readInt();
  512. trySkip(in, szTwiddled);
  513. int nextRecord = in.readShort();
  514. //reference name is optional!
  515. if (nextRecord == RecordType.REFERENCE_NAME.id) {
  516. readStringPair(in, modules.charset, REFERENCE_NAME_RESERVED);
  517. nextRecord = in.readShort();
  518. }
  519. if (nextRecord != 0x30) {
  520. throw new IOException("Expected 0x30 as Reserved3 in a ReferenceControl record");
  521. }
  522. int szExtended = in.readInt();
  523. trySkip(in, szExtended);
  524. break;
  525. case MODULE_TERMINATOR:
  526. int endOfModulesReserved = in.readInt();
  527. //must be 0;
  528. break;
  529. default:
  530. if (type.getConstantLength() > -1) {
  531. trySkip(in, type.getConstantLength());
  532. } else {
  533. int recordLength = in.readInt();
  534. trySkip(in, recordLength);
  535. }
  536. break;
  537. }
  538. }
  539. } catch (final IOException e) {
  540. throw new IOException(
  541. "Error occurred while reading macros at section id "
  542. + recordId + " (" + HexDump.shortToHex(recordId) + ")", e);
  543. }
  544. }
  545. }
  546. private ASCIIUnicodeStringPair readStringPair(RLEDecompressingInputStream in,
  547. Charset charset, int reservedByte) throws IOException {
  548. return readStringPair(in, charset, reservedByte, true);
  549. }
  550. private ASCIIUnicodeStringPair readStringPair(RLEDecompressingInputStream in,
  551. Charset charset, int reservedByte,
  552. boolean throwOnUnexpectedReservedByte) throws IOException {
  553. int nameLength = in.readInt();
  554. String ascii = readString(in, nameLength, charset);
  555. int reserved = in.readShort();
  556. if (reserved != reservedByte) {
  557. if (throwOnUnexpectedReservedByte) {
  558. throw new IOException("Expected " + Integer.toHexString(reservedByte) +
  559. "after name before Unicode name, but found: " +
  560. Integer.toHexString(reserved));
  561. } else {
  562. return new ASCIIUnicodeStringPair(ascii, reserved);
  563. }
  564. }
  565. int unicodeNameRecordLength = in.readInt();
  566. String unicode = readUnicodeString(in, unicodeNameRecordLength);
  567. return new ASCIIUnicodeStringPair(ascii, unicode);
  568. }
  569. protected void readNameMapRecords(InputStream is,
  570. Map<String, String> moduleNames, Charset charset) throws IOException {
  571. //see 2.3.3 PROJECTwm Stream: Module Name Information
  572. //multibytecharstring
  573. String mbcs = null;
  574. String unicode = null;
  575. //arbitrary sanity threshold
  576. final int maxNameRecords = 10000;
  577. int records = 0;
  578. while (++records < maxNameRecords) {
  579. try {
  580. int b = IOUtils.readByte(is);
  581. //check for two 0x00 that mark end of record
  582. if (b == 0) {
  583. b = IOUtils.readByte(is);
  584. if (b == 0) {
  585. return;
  586. }
  587. }
  588. mbcs = readMBCS(b, is, charset, MAX_STRING_LENGTH);
  589. } catch (EOFException e) {
  590. return;
  591. }
  592. try {
  593. unicode = readUnicode(is, MAX_STRING_LENGTH);
  594. } catch (EOFException e) {
  595. return;
  596. }
  597. if (mbcs.trim().length() > 0 && unicode.trim().length() > 0) {
  598. moduleNames.put(mbcs, unicode);
  599. }
  600. }
  601. LOGGER.atWarn().log("Hit max name records to read (" + maxNameRecords + "). Stopped early.");
  602. }
  603. private static String readUnicode(InputStream is, int maxLength) throws IOException {
  604. //reads null-terminated unicode string
  605. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  606. int b0 = IOUtils.readByte(is);
  607. int b1 = IOUtils.readByte(is);
  608. int read = 2;
  609. while ((b0 + b1) != 0 && read < maxLength) {
  610. bos.write(b0);
  611. bos.write(b1);
  612. b0 = IOUtils.readByte(is);
  613. b1 = IOUtils.readByte(is);
  614. read += 2;
  615. }
  616. if (read >= maxLength) {
  617. LOGGER.atWarn().log("stopped reading unicode name after {} bytes", box(read));
  618. }
  619. return new String (bos.toByteArray(), StandardCharsets.UTF_16LE);
  620. }
  621. private static String readMBCS(int firstByte, InputStream is, Charset charset, int maxLength) throws IOException {
  622. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  623. int len = 0;
  624. int b = firstByte;
  625. while (b > 0 && len < maxLength) {
  626. ++len;
  627. bos.write(b);
  628. b = IOUtils.readByte(is);
  629. }
  630. return new String(bos.toByteArray(), charset);
  631. }
  632. /**
  633. * Read <tt>length</tt> bytes of MBCS (multi-byte character set) characters from the stream
  634. *
  635. * @param stream the inputstream to read from
  636. * @param length number of bytes to read from stream
  637. * @param charset the character set encoding of the bytes in the stream
  638. * @return a java String in the supplied character set
  639. * @throws IOException If reading from the stream fails
  640. */
  641. private static String readString(InputStream stream, int length, Charset charset) throws IOException {
  642. byte[] buffer = IOUtils.safelyAllocate(length, MAX_STRING_LENGTH);
  643. int bytesRead = IOUtils.readFully(stream, buffer);
  644. if (bytesRead != length) {
  645. throw new IOException("Tried to read: "+length +
  646. ", but could only read: "+bytesRead);
  647. }
  648. return new String(buffer, 0, length, charset);
  649. }
  650. protected void readProjectProperties(DocumentInputStream dis,
  651. Map<String, String> moduleNameMap, ModuleMap modules) throws IOException {
  652. InputStreamReader reader = new InputStreamReader(dis, modules.charset);
  653. StringBuilder builder = new StringBuilder();
  654. char[] buffer = new char[512];
  655. int read;
  656. while ((read = reader.read(buffer)) >= 0) {
  657. builder.append(buffer, 0, read);
  658. }
  659. String properties = builder.toString();
  660. //the module name map names should be in exactly the same order
  661. //as the module names here. See 2.3.3 PROJECTwm Stream.
  662. //At some point, we might want to enforce that.
  663. for (String line : properties.split("\r\n|\n\r")) {
  664. if (!line.startsWith("[")) {
  665. String[] tokens = line.split("=");
  666. if (tokens.length > 1 && tokens[1].length() > 1
  667. && tokens[1].startsWith("\"") && tokens[1].endsWith("\"")) {
  668. // Remove any double quotes
  669. tokens[1] = tokens[1].substring(1, tokens[1].length() - 1);
  670. }
  671. if ("Document".equals(tokens[0]) && tokens.length > 1) {
  672. String mn = tokens[1].substring(0, tokens[1].indexOf("/&H"));
  673. ModuleImpl module = getModule(mn, moduleNameMap, modules);
  674. if (module != null) {
  675. module.moduleType = ModuleType.Document;
  676. } else {
  677. LOGGER.atWarn().log("couldn't find module with name: {}", mn);
  678. }
  679. } else if ("Module".equals(tokens[0]) && tokens.length > 1) {
  680. ModuleImpl module = getModule(tokens[1], moduleNameMap, modules);
  681. if (module != null) {
  682. module.moduleType = ModuleType.Module;
  683. } else {
  684. LOGGER.atWarn().log("couldn't find module with name: {}", tokens[1]);
  685. }
  686. } else if ("Class".equals(tokens[0]) && tokens.length > 1) {
  687. ModuleImpl module = getModule(tokens[1], moduleNameMap, modules);
  688. if (module != null) {
  689. module.moduleType = ModuleType.Class;
  690. } else {
  691. LOGGER.atWarn().log("couldn't find module with name: {}", tokens[1]);
  692. }
  693. }
  694. }
  695. }
  696. }
  697. //can return null!
  698. private ModuleImpl getModule(String moduleName, Map<String, String> moduleNameMap, ModuleMap moduleMap) {
  699. if (moduleNameMap.containsKey(moduleName)) {
  700. return moduleMap.get(moduleNameMap.get(moduleName));
  701. }
  702. return moduleMap.get(moduleName);
  703. }
  704. private String readUnicodeString(RLEDecompressingInputStream in, int unicodeNameRecordLength) throws IOException {
  705. byte[] buffer = IOUtils.safelyAllocate(unicodeNameRecordLength, MAX_STRING_LENGTH);
  706. int bytesRead = IOUtils.readFully(in, buffer);
  707. if (bytesRead != unicodeNameRecordLength) {
  708. throw new EOFException();
  709. }
  710. return new String(buffer, StringUtil.UTF16LE);
  711. }
  712. /**
  713. * Sometimes the offset record in the dirstream is incorrect, but the macro can still be found.
  714. * This will try to find the the first RLEDecompressing stream that starts with "Attribute".
  715. * This relies on some, er, heuristics, admittedly.
  716. *
  717. * @param is full module inputstream to read
  718. * @return uncompressed bytes if found, <code>null</code> otherwise
  719. * @throws IOException for a true IOException copying the is to a byte array
  720. */
  721. private static byte[] findCompressedStreamWBruteForce(InputStream is) throws IOException {
  722. //buffer to memory for multiple tries
  723. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  724. IOUtils.copy(is, bos);
  725. byte[] compressed = bos.toByteArray();
  726. byte[] decompressed = null;
  727. for (int i = 0; i < compressed.length; i++) {
  728. if (compressed[i] == 0x01 && i < compressed.length-1) {
  729. int w = LittleEndian.getUShort(compressed, i+1);
  730. if (w <= 0 || (w & 0x7000) != 0x3000) {
  731. continue;
  732. }
  733. decompressed = tryToDecompress(new ByteArrayInputStream(compressed, i, compressed.length - i));
  734. if (decompressed != null) {
  735. if (decompressed.length > 9) {
  736. //this is a complete hack. The challenge is that there
  737. //can be many 0 length or junk streams that are uncompressed
  738. //look in the first 20 characters for "Attribute"
  739. int firstX = Math.min(20, decompressed.length);
  740. String start = new String(decompressed, 0, firstX, StringUtil.WIN_1252);
  741. if (start.contains("Attribute")) {
  742. return decompressed;
  743. }
  744. }
  745. }
  746. }
  747. }
  748. return decompressed;
  749. }
  750. private static byte[] tryToDecompress(InputStream is) {
  751. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  752. try {
  753. IOUtils.copy(new RLEDecompressingInputStream(is), bos);
  754. } catch (IllegalArgumentException | IOException | IllegalStateException e){
  755. return null;
  756. }
  757. return bos.toByteArray();
  758. }
  759. }