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.

Ole10Native.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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.IOException;
  17. import java.io.OutputStream;
  18. import java.nio.charset.Charset;
  19. import java.nio.charset.StandardCharsets;
  20. import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
  21. import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
  22. import org.apache.poi.util.IOUtils;
  23. import org.apache.poi.util.LittleEndianByteArrayInputStream;
  24. import org.apache.poi.util.LittleEndianConsts;
  25. import org.apache.poi.util.LittleEndianInput;
  26. import org.apache.poi.util.LittleEndianOutputStream;
  27. import org.apache.poi.util.StringUtil;
  28. /**
  29. * Represents an Ole10Native record which is wrapped around certain binary
  30. * files being embedded in OLE2 documents.<p>
  31. *
  32. * Ole10Native objects come in different shapes:
  33. * <ul>
  34. * <li>unparsed: we can't identify it's structure</li>
  35. * <li>compact: same as unparsed but with a leading flag</li>
  36. * <li>parsed - Ole-Class "Package": data + ASCII label,command,filename</li>
  37. * <li>parsed - Ole-Class "Package2": as above plus UTF16 label,command,filename</li>
  38. * </ul>
  39. */
  40. @SuppressWarnings("unused")
  41. public class Ole10Native {
  42. public static final String OLE10_NATIVE = "\u0001Ole10Native";
  43. private static final Charset ISO1 = StandardCharsets.ISO_8859_1;
  44. // arbitrarily selected; may need to increase
  45. private static final int DEFAULT_MAX_RECORD_LENGTH = 100_000_000;
  46. private static int MAX_RECORD_LENGTH = DEFAULT_MAX_RECORD_LENGTH;
  47. // arbitrarily selected; may need to increase
  48. private static final int DEFAULT_MAX_STRING_LENGTH = 1024;
  49. private static int MAX_STRING_LENGTH = DEFAULT_MAX_STRING_LENGTH;
  50. /**
  51. * Default content of the \u0001Ole entry
  52. */
  53. private static final byte[] OLE_MARKER_BYTES =
  54. {1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  55. private static final String OLE_MARKER_NAME = "\u0001Ole";
  56. // 4 bytes, total size of record not including this field
  57. private int totalSize;
  58. // 2 bytes, unknown, mostly [02 00]
  59. private short flags1 = 2;
  60. // ASCIIZ, stored in this field without the terminating zero
  61. private String label;
  62. // ASCIIZ, stored in this field without the terminating zero
  63. private String fileName;
  64. // 2 bytes, unknown, mostly [00 00]
  65. private short flags2;
  66. // see below
  67. private short unknown1 = 3;
  68. // ASCIIZ, stored in this field without the terminating zero
  69. private String command;
  70. // varying size, the actual native data
  71. private byte[] dataBuffer;
  72. // UTF16-LE String with leading length
  73. private String command2;
  74. // UTF16-LE String with leading length
  75. private String label2;
  76. // UTF16-LE String with leading length
  77. private String fileName2;
  78. /**
  79. * the field encoding mode - merely a try-and-error guess ...
  80. **/
  81. private enum EncodingMode {
  82. /**
  83. * the data is stored in parsed format - including label, command, etc.
  84. */
  85. parsed,
  86. /**
  87. * the data is stored raw after the length field
  88. */
  89. unparsed,
  90. /**
  91. * the data is stored raw after the length field and the flags1 field
  92. */
  93. compact
  94. }
  95. private EncodingMode mode;
  96. /**
  97. * Creates an instance of this class from an embedded OLE Object. The OLE Object is expected
  98. * to include a stream &quot;{01}Ole10Native&quot; which contains the actual
  99. * data relevant for this class.
  100. *
  101. * @param poifs POI Filesystem object
  102. * @return Returns an instance of this class
  103. * @throws IOException on IO error
  104. * @throws Ole10NativeException on invalid or unexcepted data format
  105. */
  106. public static Ole10Native createFromEmbeddedOleObject(POIFSFileSystem poifs) throws IOException, Ole10NativeException {
  107. return createFromEmbeddedOleObject(poifs.getRoot());
  108. }
  109. /**
  110. * Creates an instance of this class from an embedded OLE Object. The OLE Object is expected
  111. * to include a stream &quot;{01}Ole10Native&quot; which contains the actual
  112. * data relevant for this class.
  113. *
  114. * @param directory POI Filesystem object
  115. * @return Returns an instance of this class
  116. * @throws IOException on IO error
  117. * @throws Ole10NativeException on invalid or unexcepted data format
  118. */
  119. public static Ole10Native createFromEmbeddedOleObject(DirectoryNode directory) throws IOException, Ole10NativeException {
  120. DocumentEntry nativeEntry = (DocumentEntry) directory.getEntry(OLE10_NATIVE);
  121. try (DocumentInputStream dis = directory.createDocumentInputStream(nativeEntry)) {
  122. byte[] data = IOUtils.toByteArray(dis, nativeEntry.getSize(), MAX_RECORD_LENGTH);
  123. return new Ole10Native(data, 0);
  124. }
  125. }
  126. /**
  127. * @param length the max record length allowed for Ole10Native
  128. */
  129. public static void setMaxRecordLength(int length) {
  130. MAX_RECORD_LENGTH = length;
  131. }
  132. /**
  133. * @return the max record length allowed for Ole10Native
  134. */
  135. public static int getMaxRecordLength() {
  136. return MAX_RECORD_LENGTH;
  137. }
  138. /**
  139. * @param length the max string length allowed for Ole10Native
  140. */
  141. public static void setMaxStringLength(int length) {
  142. MAX_STRING_LENGTH = length;
  143. }
  144. /**
  145. * @return the max string length allowed for Ole10Native
  146. */
  147. public static int getMaxStringLength() {
  148. return MAX_STRING_LENGTH;
  149. }
  150. /**
  151. * Creates an instance and fills the fields based on ... the fields
  152. */
  153. public Ole10Native(String label, String filename, String command, byte[] data) {
  154. setLabel(label);
  155. setFileName(filename);
  156. setCommand(command);
  157. command2 = command;
  158. setDataBuffer(data);
  159. mode = EncodingMode.parsed;
  160. }
  161. /**
  162. * Creates an instance and fills the fields based on the data in the given buffer.
  163. *
  164. * @param data The buffer containing the Ole10Native record
  165. * @param offset The start offset of the record in the buffer
  166. * @throws Ole10NativeException on invalid or unexcepted data format
  167. */
  168. public Ole10Native(final byte[] data, final int offset) throws Ole10NativeException {
  169. LittleEndianByteArrayInputStream leis = new LittleEndianByteArrayInputStream(data, offset);
  170. totalSize = leis.readInt();
  171. leis.limit(totalSize + LittleEndianConsts.INT_SIZE);
  172. leis.mark(0);
  173. try {
  174. flags1 = leis.readShort();
  175. if (flags1 == 2) {
  176. leis.mark(0);
  177. // some files like equations don't have a valid filename,
  178. // but somehow encode the formula right away in the ole10 header
  179. boolean validFileName = !Character.isISOControl(leis.readByte());
  180. leis.reset();
  181. if (validFileName) {
  182. readParsed(leis);
  183. } else {
  184. readCompact(leis);
  185. }
  186. } else {
  187. leis.reset();
  188. readUnparsed(leis);
  189. }
  190. } catch (IOException e) {
  191. throw new Ole10NativeException("Invalid Ole10Native", e);
  192. }
  193. }
  194. private void readParsed(LittleEndianByteArrayInputStream leis) throws Ole10NativeException, IOException {
  195. mode = EncodingMode.parsed;
  196. label = readAsciiZ(leis);
  197. fileName = readAsciiZ(leis);
  198. flags2 = leis.readShort();
  199. unknown1 = leis.readShort();
  200. command = readAsciiLen(leis);
  201. dataBuffer = IOUtils.toByteArray(leis, leis.readInt(), MAX_RECORD_LENGTH);
  202. leis.mark(0);
  203. short lowSize = leis.readShort();
  204. if (lowSize != 0) {
  205. leis.reset();
  206. command2 = readUtf16(leis);
  207. label2 = readUtf16(leis);
  208. fileName2 = readUtf16(leis);
  209. }
  210. }
  211. private void readCompact(LittleEndianByteArrayInputStream leis) throws IOException {
  212. mode = EncodingMode.compact;
  213. dataBuffer = IOUtils.toByteArray(leis, totalSize - LittleEndianConsts.SHORT_SIZE, MAX_RECORD_LENGTH);
  214. }
  215. private void readUnparsed(LittleEndianByteArrayInputStream leis) throws IOException {
  216. mode = EncodingMode.unparsed;
  217. dataBuffer = IOUtils.toByteArray(leis, totalSize, MAX_RECORD_LENGTH);
  218. }
  219. /**
  220. * Add the \1OLE marker entry, which is not the Ole10Native entry.
  221. * Beside this "\u0001Ole" record there were several other records, e.g. CompObj,
  222. * OlePresXXX, but it seems, that they aren't necessary
  223. */
  224. public static void createOleMarkerEntry(final DirectoryEntry parent) throws IOException {
  225. if (!parent.hasEntry(OLE_MARKER_NAME)) {
  226. parent.createDocument(OLE_MARKER_NAME, new UnsynchronizedByteArrayInputStream(OLE_MARKER_BYTES));
  227. }
  228. }
  229. /**
  230. * Add the \1OLE marker entry, which is not the Ole10Native entry.
  231. * Beside this "\u0001Ole" record there were several other records, e.g. CompObj,
  232. * OlePresXXX, but it seems, that they aren't necessary
  233. */
  234. public static void createOleMarkerEntry(final POIFSFileSystem poifs) throws IOException {
  235. createOleMarkerEntry(poifs.getRoot());
  236. }
  237. /**
  238. * Read zero terminated string (ASCIIZ).
  239. */
  240. private static String readAsciiZ(LittleEndianInput is) throws Ole10NativeException {
  241. // arbitrary sized buffer - not sure how big strings can get in an Ole10 record
  242. byte[] buf = new byte[MAX_STRING_LENGTH];
  243. for (int i=0; i<buf.length; i++) {
  244. if ((buf[i] = is.readByte()) == 0) {
  245. return StringUtil.getFromCompressedUnicode(buf, 0, i);
  246. }
  247. }
  248. throw new Ole10NativeException("AsciiZ string was not null terminated after " + MAX_STRING_LENGTH + " bytes - Exiting.");
  249. }
  250. private static String readAsciiLen(LittleEndianByteArrayInputStream leis) throws IOException {
  251. int size = leis.readInt();
  252. byte[] buf = IOUtils.toByteArray(leis, size, MAX_STRING_LENGTH);
  253. return (buf.length == 0) ? "" : StringUtil.getFromCompressedUnicode(buf, 0, size - 1);
  254. }
  255. private static String readUtf16(LittleEndianByteArrayInputStream leis) throws IOException {
  256. int size = leis.readInt();
  257. byte[] buf = IOUtils.toByteArray(leis, size * 2, MAX_STRING_LENGTH);
  258. return StringUtil.getFromUnicodeLE(buf, 0, size);
  259. }
  260. /**
  261. * Returns the value of the totalSize field - the total length of the
  262. * structure is totalSize + 4 (value of this field + size of this field).
  263. *
  264. * @return the totalSize
  265. */
  266. public int getTotalSize() {
  267. return totalSize;
  268. }
  269. /**
  270. * Returns flags1 - currently unknown - usually 0x0002.
  271. *
  272. * @return the flags1
  273. */
  274. public short getFlags1() {
  275. return flags1;
  276. }
  277. /**
  278. * Returns the label field - usually the name of the file (without
  279. * directory) but probably may be any name specified during
  280. * packaging/embedding the data.
  281. *
  282. * @return the label
  283. */
  284. public String getLabel() {
  285. return label;
  286. }
  287. /**
  288. * Returns the fileName field - usually the name of the file being embedded
  289. * including the full path.
  290. *
  291. * @return the fileName
  292. */
  293. public String getFileName() {
  294. return fileName;
  295. }
  296. /**
  297. * Returns flags2 - currently unknown - mostly 0x0000.
  298. *
  299. * @return the flags2
  300. */
  301. public short getFlags2() {
  302. return flags2;
  303. }
  304. /**
  305. * Returns unknown1 field - currently unknown.
  306. *
  307. * @return the unknown1
  308. */
  309. public short getUnknown1() {
  310. return unknown1;
  311. }
  312. /**
  313. * Returns the command field - usually the name of the file being embedded
  314. * including the full path, may be a command specified during embedding the
  315. * file.
  316. *
  317. * @return the command
  318. */
  319. public String getCommand() {
  320. return command;
  321. }
  322. /**
  323. * Returns the size of the embedded file. If the size is 0 (zero), no data
  324. * has been embedded. To be sure, that no data has been embedded, check
  325. * whether {@link #getDataBuffer()} returns {@code null}.
  326. *
  327. * @return the dataSize
  328. */
  329. public int getDataSize() {
  330. return dataBuffer.length;
  331. }
  332. /**
  333. * Returns the buffer containing the embedded file's data, or
  334. * {@code null} if no data was embedded. Note that an embedding may
  335. * provide information about the data, but the actual data is not included.
  336. * (So label, filename etc. are available, but this method returns
  337. * {@code null}.)
  338. *
  339. * @return the dataBuffer
  340. */
  341. public byte[] getDataBuffer() {
  342. return dataBuffer;
  343. }
  344. /**
  345. * Have the contents printer out into an OutputStream, used when writing a
  346. * file back out to disk (Normally, atom classes will keep their bytes
  347. * around, but non atom classes will just request the bytes from their
  348. * children, then chuck on their header and return)
  349. */
  350. public void writeOut(OutputStream out) throws IOException {
  351. // byte intbuf[] = new byte[LittleEndianConsts.INT_SIZE];
  352. // byte shortbuf[] = new byte[LittleEndianConsts.SHORT_SIZE];
  353. @SuppressWarnings("resource")
  354. LittleEndianOutputStream leosOut = new LittleEndianOutputStream(out);
  355. switch (mode) {
  356. case parsed: {
  357. UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
  358. try (LittleEndianOutputStream leos = new LittleEndianOutputStream(bos)) {
  359. // total size, will be determined later ..
  360. leos.writeShort(getFlags1());
  361. leos.write(getLabel().getBytes(ISO1));
  362. leos.write(0);
  363. leos.write(getFileName().getBytes(ISO1));
  364. leos.write(0);
  365. leos.writeShort(getFlags2());
  366. leos.writeShort(getUnknown1());
  367. leos.writeInt(getCommand().length() + 1);
  368. leos.write(getCommand().getBytes(ISO1));
  369. leos.write(0);
  370. leos.writeInt(getDataSize());
  371. leos.write(getDataBuffer());
  372. if (command2 == null || label2 == null || fileName2 == null) {
  373. leos.writeShort(0);
  374. } else {
  375. leos.writeUInt(command2.length());
  376. leos.write(StringUtil.getToUnicodeLE(command2));
  377. leos.writeUInt(label2.length());
  378. leos.write(StringUtil.getToUnicodeLE(label2));
  379. leos.writeUInt(fileName2.length());
  380. leos.write(StringUtil.getToUnicodeLE(fileName2));
  381. }
  382. }
  383. // total size
  384. leosOut.writeInt(bos.size());
  385. bos.writeTo(out);
  386. break;
  387. }
  388. case compact:
  389. leosOut.writeInt(getDataSize() + LittleEndianConsts.SHORT_SIZE);
  390. leosOut.writeShort(getFlags1());
  391. out.write(getDataBuffer());
  392. break;
  393. default:
  394. case unparsed:
  395. leosOut.writeInt(getDataSize());
  396. out.write(getDataBuffer());
  397. break;
  398. }
  399. }
  400. public void setFlags1(short flags1) {
  401. this.flags1 = flags1;
  402. }
  403. public void setFlags2(short flags2) {
  404. this.flags2 = flags2;
  405. }
  406. public void setLabel(String label) {
  407. this.label = label;
  408. }
  409. public void setFileName(String fileName) {
  410. this.fileName = fileName;
  411. }
  412. public void setCommand(String command) {
  413. this.command = command;
  414. }
  415. public void setUnknown1(short unknown1) {
  416. this.unknown1 = unknown1;
  417. }
  418. public void setDataBuffer(byte[] dataBuffer) {
  419. this.dataBuffer = dataBuffer.clone();
  420. }
  421. /**
  422. * Get Command string of UTF16 extended OLE packages or {@code null} if not set or not UTF16 extended
  423. */
  424. public String getCommand2() {
  425. return command2;
  426. }
  427. /**
  428. * Set Command string for UTF16 extended OLE packages or {@code null} if not set or not UTF16 extended
  429. */
  430. public void setCommand2(String command2) {
  431. this.command2 = command2;
  432. }
  433. /**
  434. * Get Label string for UTF16 extended OLE packages or {@code null} if not set or not UTF16 extended
  435. */
  436. public String getLabel2() {
  437. return label2;
  438. }
  439. /**
  440. * Set Label string for UTF16 extended OLE packages or {@code null} if not set or not UTF16 extended
  441. */
  442. public void setLabel2(String label2) {
  443. this.label2 = label2;
  444. }
  445. /**
  446. * Get filename string for UTF16 extended OLE packages or {@code null} if not set or not UTF16 extended
  447. */
  448. public String getFileName2() {
  449. return fileName2;
  450. }
  451. /**
  452. * Set filename string for UTF16 extended OLE packages or {@code null} if not set or not UTF16 extended
  453. */
  454. public void setFileName2(String fileName2) {
  455. this.fileName2 = fileName2;
  456. }
  457. }