Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Ole10Native.java 17KB

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