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.

FileMagic.java 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 static org.apache.poi.poifs.common.POIFSConstants.OOXML_FILE_HEADER;
  17. import static org.apache.poi.poifs.common.POIFSConstants.RAW_XML_FILE_HEADER;
  18. import java.io.BufferedInputStream;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.util.Arrays;
  24. import org.apache.poi.poifs.storage.HeaderBlockConstants;
  25. import org.apache.poi.util.IOUtils;
  26. import org.apache.poi.util.LittleEndian;
  27. import org.apache.poi.util.LocaleUtil;
  28. /**
  29. * The file magic number, i.e. the file identification based on the first bytes
  30. * of the file
  31. */
  32. public enum FileMagic {
  33. /** OLE2 / BIFF8+ stream used for Office 97 and higher documents */
  34. OLE2(HeaderBlockConstants._signature),
  35. /** OOXML / ZIP stream */
  36. OOXML(OOXML_FILE_HEADER),
  37. /** XML file */
  38. XML(RAW_XML_FILE_HEADER),
  39. /** BIFF2 raw stream - for Excel 2 */
  40. BIFF2(new byte[]{
  41. 0x09, 0x00, // sid=0x0009
  42. 0x04, 0x00, // size=0x0004
  43. 0x00, 0x00, // unused
  44. '?', 0x00 // '?' = multiple values
  45. }),
  46. /** BIFF3 raw stream - for Excel 3 */
  47. BIFF3(new byte[]{
  48. 0x09, 0x02, // sid=0x0209
  49. 0x06, 0x00, // size=0x0006
  50. 0x00, 0x00, // unused
  51. '?', 0x00 // '?' = multiple values
  52. }),
  53. /** BIFF4 raw stream - for Excel 4 */
  54. BIFF4(new byte[]{
  55. 0x09, 0x04, // sid=0x0409
  56. 0x06, 0x00, // size=0x0006
  57. 0x00, 0x00, // unused
  58. '?', 0x00 // '? = multiple values
  59. },new byte[]{
  60. 0x09, 0x04, // sid=0x0409
  61. 0x06, 0x00, // size=0x0006
  62. 0x00, 0x00, // unused
  63. 0x00, 0x01
  64. }),
  65. /** Old MS Write raw stream */
  66. MSWRITE(
  67. new byte[]{0x31, (byte)0xbe, 0x00, 0x00 },
  68. new byte[]{0x32, (byte)0xbe, 0x00, 0x00 }),
  69. /** RTF document */
  70. RTF("{\\rtf"),
  71. /** PDF document */
  72. PDF("%PDF"),
  73. /** Some different HTML documents */
  74. HTML("<!DOCTYP",
  75. "<html","\n\r<html","\r\n<html","\r<html","\n<html",
  76. "<HTML","\r\n<HTML","\n\r<HTML","\r<HTML","\n<HTML"),
  77. WORD2(new byte[]{ (byte)0xdb, (byte)0xa5, 0x2d, 0x00}),
  78. /** JPEG image */
  79. JPEG(
  80. new byte[]{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xDB },
  81. new byte[]{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xE0, '?', '?', 'J', 'F', 'I', 'F', 0x00, 0x01 },
  82. new byte[]{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xEE },
  83. new byte[]{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xE1, '?', '?', 'E', 'x', 'i', 'f', 0x00, 0x00 }),
  84. /** GIF image */
  85. GIF("GIF87a","GIF89a"),
  86. /** PNG Image */
  87. PNG(new byte[]{ (byte)0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A }),
  88. /** TIFF Image */
  89. TIFF("II*\u0000", "MM\u0000*" ),
  90. /** WMF image with a placeable header */
  91. WMF(new byte[]{ (byte)0xD7, (byte)0xCD, (byte)0xC6, (byte)0x9A }),
  92. /** EMF image */
  93. EMF(new byte[]{
  94. 1, 0, 0, 0,
  95. '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
  96. '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
  97. ' ', 'E', 'M', 'F'
  98. }),
  99. /** BMP image */
  100. BMP(new byte[]{'B','M'}),
  101. // keep UNKNOWN always as last enum!
  102. /** UNKNOWN magic */
  103. UNKNOWN(new byte[0]);
  104. // update this if a longer pattern is added
  105. final static int MAX_PATTERN_LENGTH = 44;
  106. final byte[][] magic;
  107. FileMagic(long magic) {
  108. this.magic = new byte[1][8];
  109. LittleEndian.putLong(this.magic[0], 0, magic);
  110. }
  111. FileMagic(byte[]... magic) {
  112. this.magic = magic;
  113. }
  114. FileMagic(String... magic) {
  115. this.magic = new byte[magic.length][];
  116. int i=0;
  117. for (String s : magic) {
  118. this.magic[i++] = s.getBytes(LocaleUtil.CHARSET_1252);
  119. }
  120. }
  121. public static FileMagic valueOf(byte[] magic) {
  122. for (FileMagic fm : values()) {
  123. for (byte[] ma : fm.magic) {
  124. // don't try to match if the given byte-array is too short
  125. // for this pattern anyway
  126. if(magic.length < ma.length) {
  127. continue;
  128. }
  129. if (findMagic(ma, magic)) {
  130. return fm;
  131. }
  132. }
  133. }
  134. return UNKNOWN;
  135. }
  136. private static boolean findMagic(byte[] expected, byte[] actual) {
  137. int i=0;
  138. for (byte expectedByte : expected) {
  139. if (actual[i++] != expectedByte && expectedByte != '?') {
  140. return false;
  141. }
  142. }
  143. return true;
  144. }
  145. /**
  146. * Get the file magic of the supplied {@link File}<p>
  147. *
  148. * Even if this method returns {@link FileMagic#UNKNOWN} it could potentially mean,
  149. * that the ZIP stream has leading junk bytes
  150. *
  151. * @param inp a file to be identified
  152. */
  153. public static FileMagic valueOf(final File inp) throws IOException {
  154. try (FileInputStream fis = new FileInputStream(inp)) {
  155. // read as many bytes as possible, up to the required number of bytes
  156. byte[] data = new byte[MAX_PATTERN_LENGTH];
  157. int read = IOUtils.readFully(fis, data, 0, MAX_PATTERN_LENGTH);
  158. if(read == -1) {
  159. return FileMagic.UNKNOWN;
  160. }
  161. // only use the bytes that could be read
  162. data = Arrays.copyOf(data, read);
  163. return FileMagic.valueOf(data);
  164. }
  165. }
  166. /**
  167. * Get the file magic of the supplied InputStream (which MUST
  168. * support mark and reset).<p>
  169. *
  170. * If unsure if your InputStream does support mark / reset,
  171. * use {@link #prepareToCheckMagic(InputStream)} to wrap it and make
  172. * sure to always use that, and not the original!<p>
  173. *
  174. * Even if this method returns {@link FileMagic#UNKNOWN} it could potentially mean,
  175. * that the ZIP stream has leading junk bytes
  176. *
  177. * @param inp An InputStream which supports either mark/reset
  178. */
  179. public static FileMagic valueOf(InputStream inp) throws IOException {
  180. if (!inp.markSupported()) {
  181. throw new IOException("getFileMagic() only operates on streams which support mark(int)");
  182. }
  183. // Grab the first bytes of this stream
  184. byte[] data = IOUtils.peekFirstNBytes(inp, MAX_PATTERN_LENGTH);
  185. return FileMagic.valueOf(data);
  186. }
  187. /**
  188. * Checks if an {@link InputStream} can be reset (i.e. used for checking the header magic) and wraps it if not
  189. *
  190. * @param stream stream to be checked for wrapping
  191. * @return a mark enabled stream
  192. */
  193. public static InputStream prepareToCheckMagic(InputStream stream) {
  194. if (stream.markSupported()) {
  195. return stream;
  196. }
  197. // we used to process the data via a PushbackInputStream, but user code could provide a too small one
  198. // so we use a BufferedInputStream instead now
  199. return new BufferedInputStream(stream);
  200. }
  201. }