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.

IOUtils.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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.util;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.Closeable;
  18. import java.io.EOFException;
  19. import java.io.File;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import java.io.PushbackInputStream;
  25. import java.nio.ByteBuffer;
  26. import java.nio.channels.ReadableByteChannel;
  27. import java.util.Arrays;
  28. import java.util.Locale;
  29. import java.util.zip.CRC32;
  30. import java.util.zip.Checksum;
  31. import org.apache.logging.log4j.LogManager;
  32. import org.apache.logging.log4j.Logger;
  33. import org.apache.poi.EmptyFileException;
  34. @Internal
  35. public final class IOUtils {
  36. private static final Logger LOG = LogManager.getLogger(IOUtils.class);
  37. /**
  38. * The default buffer size to use for the skip() methods.
  39. */
  40. private static final int SKIP_BUFFER_SIZE = 2048;
  41. private static byte[] SKIP_BYTE_BUFFER;
  42. /**
  43. * The current set global allocation limit override,
  44. * -1 means limits are applied per record type.
  45. */
  46. private static int BYTE_ARRAY_MAX_OVERRIDE = -1;
  47. private IOUtils() {
  48. // no instances of this class
  49. }
  50. /**
  51. * If this value is set to > 0, {@link #safelyAllocate(long, int)} will ignore the
  52. * maximum record length parameter.
  53. *
  54. * This is designed to allow users to bypass the hard-coded maximum record lengths
  55. * if they are willing to accept the risk of allocating memory up to the size specified.
  56. *
  57. * It also allows to impose a lower limit than used for very memory constrained systems.
  58. *
  59. * Note: This is an per-allocation limit and does not allow to limit overall sum of allocations!
  60. *
  61. * Use -1 for using the limits specified per record-type.
  62. *
  63. * @param maxOverride The maximum number of bytes that should be possible to be allocated in one step.
  64. * @since 4.0.0
  65. */
  66. @SuppressWarnings("unused")
  67. public static void setByteArrayMaxOverride(int maxOverride) {
  68. BYTE_ARRAY_MAX_OVERRIDE = maxOverride;
  69. }
  70. /**
  71. * Peeks at the first 8 bytes of the stream. Returns those bytes, but
  72. * with the stream unaffected. Requires a stream that supports mark/reset,
  73. * or a PushbackInputStream. If the stream has >0 but <8 bytes,
  74. * remaining bytes will be zero.
  75. * @throws EmptyFileException if the stream is empty
  76. */
  77. public static byte[] peekFirst8Bytes(InputStream stream) throws IOException, EmptyFileException {
  78. return peekFirstNBytes(stream, 8);
  79. }
  80. private static void checkByteSizeLimit(int length) {
  81. if(BYTE_ARRAY_MAX_OVERRIDE != -1 && length > BYTE_ARRAY_MAX_OVERRIDE) {
  82. throwRFE(length, BYTE_ARRAY_MAX_OVERRIDE);
  83. }
  84. }
  85. /**
  86. * Peeks at the first N bytes of the stream. Returns those bytes, but
  87. * with the stream unaffected. Requires a stream that supports mark/reset,
  88. * or a PushbackInputStream. If the stream has >0 but <N bytes,
  89. * remaining bytes will be zero.
  90. * @throws EmptyFileException if the stream is empty
  91. */
  92. public static byte[] peekFirstNBytes(InputStream stream, int limit) throws IOException, EmptyFileException {
  93. checkByteSizeLimit(limit);
  94. stream.mark(limit);
  95. ByteArrayOutputStream bos = new ByteArrayOutputStream(limit);
  96. copy(new BoundedInputStream(stream, limit), bos);
  97. int readBytes = bos.size();
  98. if (readBytes == 0) {
  99. throw new EmptyFileException();
  100. }
  101. if (readBytes < limit) {
  102. bos.write(new byte[limit-readBytes]);
  103. }
  104. byte[] peekedBytes = bos.toByteArray();
  105. if(stream instanceof PushbackInputStream) {
  106. PushbackInputStream pin = (PushbackInputStream)stream;
  107. pin.unread(peekedBytes, 0, readBytes);
  108. } else {
  109. stream.reset();
  110. }
  111. return peekedBytes;
  112. }
  113. /**
  114. * Reads all the data from the input stream, and returns the bytes read.
  115. *
  116. * @param stream The byte stream of data to read.
  117. * @return A byte array with the read bytes.
  118. * @throws IOException If reading data fails or EOF is encountered too early for the given length.
  119. */
  120. public static byte[] toByteArray(InputStream stream) throws IOException {
  121. return toByteArray(stream, Integer.MAX_VALUE);
  122. }
  123. /**
  124. * Reads up to {@code length} bytes from the input stream, and returns the bytes read.
  125. *
  126. * @param stream The byte stream of data to read.
  127. * @param length The maximum length to read, use Integer.MAX_VALUE to read the stream
  128. * until EOF.
  129. * @return A byte array with the read bytes.
  130. * @throws IOException If reading data fails or EOF is encountered too early for the given length.
  131. */
  132. public static byte[] toByteArray(InputStream stream, final int length) throws IOException {
  133. return toByteArray(stream, length, Integer.MAX_VALUE);
  134. }
  135. /**
  136. * Reads up to {@code length} bytes from the input stream, and returns the bytes read.
  137. *
  138. * @param stream The byte stream of data to read.
  139. * @param length The maximum length to read, use {@link Integer#MAX_VALUE} to read the stream
  140. * until EOF
  141. * @param maxLength if the input is equal to/longer than {@code maxLength} bytes,
  142. * then throw an {@link IOException} complaining about the length.
  143. * use {@link Integer#MAX_VALUE} to disable the check
  144. * @return A byte array with the read bytes.
  145. * @throws IOException If reading data fails or EOF is encountered too early for the given length.
  146. */
  147. public static byte[] toByteArray(InputStream stream, final int length, final int maxLength) throws IOException {
  148. if (length < 0L || maxLength < 0L) {
  149. throw new RecordFormatException("Can't allocate an array of length < 0");
  150. }
  151. // if (length > (long)Integer.MAX_VALUE) {
  152. // throw new RecordFormatException("Can't allocate an array > "+Integer.MAX_VALUE);
  153. // }
  154. if ((length != Integer.MAX_VALUE) || (maxLength != Integer.MAX_VALUE)) {
  155. checkLength(length, maxLength);
  156. }
  157. final int len = Math.min(length, maxLength);
  158. ByteArrayOutputStream baos = new ByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len);
  159. byte[] buffer = new byte[4096];
  160. int totalBytes = 0, readBytes;
  161. do {
  162. readBytes = stream.read(buffer, 0, Math.min(buffer.length, len-totalBytes));
  163. totalBytes += Math.max(readBytes,0);
  164. if (readBytes > 0) {
  165. baos.write(buffer, 0, readBytes);
  166. }
  167. checkByteSizeLimit(totalBytes);
  168. } while (totalBytes < len && readBytes > -1);
  169. if (maxLength != Integer.MAX_VALUE && totalBytes == maxLength) {
  170. throw new IOException("MaxLength ("+maxLength+") reached - stream seems to be invalid.");
  171. }
  172. if (len != Integer.MAX_VALUE && totalBytes < len) {
  173. throw new EOFException("unexpected EOF - expected len: "+len+" - actual len: "+totalBytes);
  174. }
  175. return baos.toByteArray();
  176. }
  177. private static void checkLength(long length, int maxLength) {
  178. if (BYTE_ARRAY_MAX_OVERRIDE > 0) {
  179. if (length > BYTE_ARRAY_MAX_OVERRIDE) {
  180. throwRFE(length, BYTE_ARRAY_MAX_OVERRIDE);
  181. }
  182. } else if (length > maxLength) {
  183. throwRFE(length, maxLength);
  184. }
  185. }
  186. /**
  187. * Returns an array (that shouldn't be written to!) of the
  188. * ByteBuffer. Will be of the requested length, or possibly
  189. * longer if that's easier.
  190. */
  191. public static byte[] toByteArray(ByteBuffer buffer, int length) {
  192. if(buffer.hasArray() && buffer.arrayOffset() == 0) {
  193. // The backing array should work out fine for us
  194. return buffer.array();
  195. }
  196. checkByteSizeLimit(length);
  197. byte[] data = new byte[length];
  198. buffer.get(data);
  199. return data;
  200. }
  201. /**
  202. * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
  203. */
  204. public static int readFully(InputStream in, byte[] b) throws IOException {
  205. return readFully(in, b, 0, b.length);
  206. }
  207. /**
  208. * <p>Same as the normal {@link InputStream#read(byte[], int, int)}, but tries to ensure
  209. * that the entire len number of bytes is read.</p>
  210. *
  211. * <p>If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  212. * the end of the file is reached after some bytes are read, returns the
  213. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  214. * bytes have been read, will return <tt>len</tt> bytes.</p>
  215. *
  216. * @param in the stream from which the data is read.
  217. * @param b the buffer into which the data is read.
  218. * @param off the start offset in array <tt>b</tt> at which the data is written.
  219. * @param len the maximum number of bytes to read.
  220. */
  221. public static int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
  222. int total = 0;
  223. while (true) {
  224. int got = in.read(b, off + total, len - total);
  225. if (got < 0) {
  226. return (total == 0) ? -1 : total;
  227. }
  228. total += got;
  229. if (total == len) {
  230. return total;
  231. }
  232. }
  233. }
  234. /**
  235. * Same as the normal <tt>channel.read(b)</tt>, but tries to ensure
  236. * that the buffer is filled completely if possible, i.e. b.remaining()
  237. * returns 0.
  238. * <p>
  239. * If the end of file is reached before any bytes are read, returns -1. If
  240. * the end of the file is reached after some bytes are read, returns the
  241. * number of bytes read. If the end of the file isn't reached before the
  242. * buffer has no more remaining capacity, will return the number of bytes
  243. * that were read.
  244. */
  245. public static int readFully(ReadableByteChannel channel, ByteBuffer b) throws IOException {
  246. int total = 0;
  247. while (true) {
  248. int got = channel.read(b);
  249. if (got < 0) {
  250. return (total == 0) ? -1 : total;
  251. }
  252. total += got;
  253. if (total == b.capacity() || b.position() == b.capacity()) {
  254. return total;
  255. }
  256. }
  257. }
  258. /**
  259. * Copies all the data from the given InputStream to the OutputStream. It
  260. * leaves both streams open, so you will still need to close them once done.
  261. *
  262. * @param inp The {@link InputStream} which provides the data
  263. * @param out The {@link OutputStream} to write the data to
  264. * @return the amount of bytes copied
  265. *
  266. * @throws IOException If copying the data fails.
  267. */
  268. public static long copy(InputStream inp, OutputStream out) throws IOException {
  269. return copy(inp, out, -1);
  270. }
  271. /**
  272. * Copies all the data from the given InputStream to the OutputStream. It
  273. * leaves both streams open, so you will still need to close them once done.
  274. *
  275. * @param inp The {@link InputStream} which provides the data
  276. * @param out The {@link OutputStream} to write the data to
  277. * @param limit limit the copied bytes - use {@code -1} for no limit
  278. * @return the amount of bytes copied
  279. *
  280. * @throws IOException If copying the data fails.
  281. */
  282. public static long copy(InputStream inp, OutputStream out, long limit) throws IOException {
  283. final byte[] buff = new byte[4096];
  284. long totalCount = 0;
  285. int readBytes = -1;
  286. do {
  287. int todoBytes = (int)((limit < 0) ? buff.length : Math.min(limit-totalCount, buff.length));
  288. if (todoBytes > 0) {
  289. readBytes = inp.read(buff, 0, todoBytes);
  290. if (readBytes > 0) {
  291. out.write(buff, 0, readBytes);
  292. totalCount += readBytes;
  293. }
  294. }
  295. } while (readBytes >= 0 && (limit == -1 || totalCount < limit));
  296. return totalCount;
  297. }
  298. /**
  299. * Copy the contents of the stream to a new file.
  300. *
  301. * @param srcStream The {@link InputStream} which provides the data
  302. * @param destFile The file where the data should be stored
  303. * @return the amount of bytes copied
  304. *
  305. * @throws IOException If the target directory does not exist and cannot be created
  306. * or if copying the data fails.
  307. */
  308. public static long copy(InputStream srcStream, File destFile) throws IOException {
  309. File destDirectory = destFile.getParentFile();
  310. if (!(destDirectory.exists() || destDirectory.mkdirs())) {
  311. throw new RuntimeException("Can't create destination directory: "+destDirectory);
  312. }
  313. try (OutputStream destStream = new FileOutputStream(destFile)) {
  314. return IOUtils.copy(srcStream, destStream);
  315. }
  316. }
  317. /**
  318. * Calculate checksum on input data
  319. */
  320. public static long calculateChecksum(byte[] data) {
  321. Checksum sum = new CRC32();
  322. sum.update(data, 0, data.length);
  323. return sum.getValue();
  324. }
  325. /**
  326. * Calculate checksum on all the data read from input stream.
  327. *
  328. * This should be more efficient than the equivalent code
  329. * {@code IOUtils.calculateChecksum(IOUtils.toByteArray(stream))}
  330. */
  331. public static long calculateChecksum(InputStream stream) throws IOException {
  332. Checksum sum = new CRC32();
  333. byte[] buf = new byte[4096];
  334. int count;
  335. while ((count = stream.read(buf)) != -1) {
  336. if (count > 0) {
  337. sum.update(buf, 0, count);
  338. }
  339. }
  340. return sum.getValue();
  341. }
  342. /**
  343. * Quietly (no exceptions) close Closable resource. In case of error it will
  344. * be printed to {@link IOUtils} class logger.
  345. *
  346. * @param closeable
  347. * resource to close
  348. */
  349. public static void closeQuietly( final Closeable closeable ) {
  350. // no need to log a NullPointerException here
  351. if(closeable == null) {
  352. return;
  353. }
  354. try {
  355. closeable.close();
  356. } catch ( Exception exc ) {
  357. LOG.atError().withThrowable(exc).log("Unable to close resource");
  358. }
  359. }
  360. /**
  361. * Skips bytes from an input byte stream.
  362. * This implementation guarantees that it will read as many bytes
  363. * as possible before giving up; this may not always be the case for
  364. * skip() implementations in subclasses of {@link InputStream}.
  365. * <p>
  366. * Note that the implementation uses {@link InputStream#read(byte[], int, int)} rather
  367. * than delegating to {@link InputStream#skip(long)}.
  368. * This means that the method may be considerably less efficient than using the actual skip implementation,
  369. * this is done to guarantee that the correct number of bytes are skipped.
  370. * </p>
  371. * <p>
  372. * This mimics POI's {@link #readFully(InputStream, byte[])}.
  373. * If the end of file is reached before any bytes are read, returns <tt>-1</tt>. If
  374. * the end of the file is reached after some bytes are read, returns the
  375. * number of bytes read. If the end of the file isn't reached before <tt>len</tt>
  376. * bytes have been read, will return <tt>len</tt> bytes.</p>
  377. * </p>
  378. * <p>
  379. * Copied nearly verbatim from commons-io 41a3e9c
  380. * </p>
  381. *
  382. * @param input byte stream to skip
  383. * @param toSkip number of bytes to skip.
  384. * @return number of bytes actually skipped.
  385. * @throws IOException if there is a problem reading the file
  386. * @throws IllegalArgumentException if toSkip is negative
  387. * @see InputStream#skip(long)
  388. *
  389. */
  390. public static long skipFully(final InputStream input, final long toSkip) throws IOException {
  391. if (toSkip < 0) {
  392. throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
  393. }
  394. if (toSkip == 0) {
  395. return 0L;
  396. }
  397. /*
  398. * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data
  399. * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer
  400. * size were variable, we would need to synch. to ensure some other thread did not create a smaller one)
  401. */
  402. if (SKIP_BYTE_BUFFER == null) {
  403. SKIP_BYTE_BUFFER = new byte[SKIP_BUFFER_SIZE];
  404. }
  405. long remain = toSkip;
  406. while (remain > 0) {
  407. // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
  408. final long n = input.read(SKIP_BYTE_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE));
  409. if (n < 0) { // EOF
  410. break;
  411. }
  412. remain -= n;
  413. }
  414. if (toSkip == remain) {
  415. return -1L;
  416. }
  417. return toSkip - remain;
  418. }
  419. public static byte[] safelyAllocate(long length, int maxLength) {
  420. safelyAllocateCheck(length, maxLength);
  421. checkByteSizeLimit((int)length);
  422. return new byte[(int)length];
  423. }
  424. public static void safelyAllocateCheck(long length, int maxLength) {
  425. if (length < 0L) {
  426. throw new RecordFormatException("Can't allocate an array of length < 0, but had " + length + " and " + maxLength);
  427. }
  428. if (length > (long)Integer.MAX_VALUE) {
  429. throw new RecordFormatException("Can't allocate an array > "+Integer.MAX_VALUE);
  430. }
  431. checkLength(length, maxLength);
  432. }
  433. public static byte[] safelyClone(byte[] src, int offset, int length, int maxLength) {
  434. if (src == null) {
  435. return null;
  436. }
  437. assert(offset >= 0 && length >= 0 && maxLength >= 0);
  438. safelyAllocateCheck(Math.min(src.length-offset,length), maxLength);
  439. return Arrays.copyOfRange(src, offset, offset+length);
  440. }
  441. /**
  442. * Simple utility function to check that you haven't hit EOF
  443. * when reading a byte.
  444. *
  445. * @param is inputstream to read
  446. * @return byte read, unless
  447. * @throws IOException on IOException or EOF if -1 is read
  448. */
  449. public static int readByte(InputStream is) throws IOException {
  450. int b = is.read();
  451. if (b == -1) {
  452. throw new EOFException();
  453. }
  454. return b;
  455. }
  456. private static void throwRFE(long length, int maxLength) {
  457. throw new RecordFormatException(String.format(Locale.ROOT, "Tried to allocate an array of length %,d" +
  458. ", but the maximum lenght for this record type is %,d.\n" +
  459. "If the file is not corrupt, please open an issue on bugzilla to request \n" +
  460. "increasing the maximum allowable size for this record type.\n"+
  461. "As a temporary workaround, consider setting a higher override value with " +
  462. "IOUtils.setByteArrayMaxOverride()",
  463. length, maxLength));
  464. }
  465. }