From 366c80c480cef79b89d92bc4a96a7b820bc084e1 Mon Sep 17 00:00:00 2001 From: Dominik Stadler Date: Mon, 27 Jan 2020 22:54:15 +0000 Subject: [PATCH] Handle empty files correctly when looking for FileMagic to avoid NegativeArraySizeException git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1873232 13f79535-47bb-0310-9956-ffa450edef68 --- src/java/org/apache/poi/poifs/filesystem/FileMagic.java | 7 +++++-- .../org/apache/poi/poifs/filesystem/TestFileMagic.java | 9 ++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/java/org/apache/poi/poifs/filesystem/FileMagic.java b/src/java/org/apache/poi/poifs/filesystem/FileMagic.java index a1035a8866..501db481a6 100644 --- a/src/java/org/apache/poi/poifs/filesystem/FileMagic.java +++ b/src/java/org/apache/poi/poifs/filesystem/FileMagic.java @@ -113,7 +113,7 @@ public enum FileMagic { final static int MAX_PATTERN_LENGTH = 44; final byte[][] magic; - + FileMagic(long magic) { this.magic = new byte[1][8]; LittleEndian.putLong(this.magic[0], 0, magic); @@ -122,7 +122,7 @@ public enum FileMagic { FileMagic(byte[]... magic) { this.magic = magic; } - + FileMagic(String... magic) { this.magic = new byte[magic.length][]; int i=0; @@ -172,6 +172,9 @@ public enum FileMagic { // read as many bytes as possible, up to the required number of bytes byte[] data = new byte[MAX_PATTERN_LENGTH]; int read = IOUtils.readFully(fis, data, 0, MAX_PATTERN_LENGTH); + if(read == -1) { + return FileMagic.UNKNOWN; + } // only use the bytes that could be read data = Arrays.copyOf(data, read); diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java index 3022abe6fd..30e0059f08 100644 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java +++ b/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java @@ -107,8 +107,15 @@ public class TestFileMagic { @Test public void testShortFile() throws IOException { // having a file shorter than 8 bytes previously caused an exception - byte[] data = new byte[] { -1, -40, -1, -32, 0 }; + fetchMagicFromData(new byte[] { -1, -40, -1, -32, 0 }); + fetchMagicFromData(new byte[] { -1, -40, -1, -32 }); + fetchMagicFromData(new byte[] { -1, -40, -1 }); + fetchMagicFromData(new byte[] { -1, -40 }); + fetchMagicFromData(new byte[] { -1 }); + fetchMagicFromData(new byte[0]); + } + private void fetchMagicFromData(byte[] data) throws IOException { File file = TempFile.createTempFile("TestFileMagic", ".bin"); try { try (FileOutputStream fos = new FileOutputStream(file)) { -- 2.39.5