This is an automated email from the ASF dual-hosted git repository.
pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git
The following commit(s) were added to refs/heads/trunk by this push:
new 1eea230212 POIFS: don't silently drop changes to a read-only file
(#1523)
1eea230212 is described below
commit 1eea230212a734b58a30a4c36e94194a01d9dd60
Author: PJ Fanning <[email protected]>
AuthorDate: Tue Nov 3 10:28:41 2026 +0100
POIFS: don't silently drop changes to a read-only file (#1523)
A POIFSFileSystem opened read-only from a file (the default for
new POIFSFileSystem(file)) reads its blocks into copies, so stream data
written to it was lost straight away, and writeFilesystem(OutputStream)
copied the original file - with the data of deleted streams that #1520
clears - whatever had been changed.
Writing stream data to such a file system now throws an
IllegalStateException before anything is freed. Changes to the entries
(delete, rename, new directories, storage CLSIDs) still work in memory,
but writeFilesystem(OutputStream) throws if there were any. An unchanged
file system is written out byte for byte as before.
Also tidies up the test from #1520: messages on the boolean assertions,
and no assertion in the finally block.
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../apache/poi/poifs/filesystem/BlockStore.java | 10 +++
.../apache/poi/poifs/filesystem/DirectoryNode.java | 5 ++
.../poi/poifs/filesystem/DocumentOutputStream.java | 3 +
.../apache/poi/poifs/filesystem/POIFSDocument.java | 3 +
.../poi/poifs/filesystem/POIFSFileSystem.java | 44 ++++++++++-
.../poi/poifs/filesystem/POIFSMiniStore.java | 5 ++
.../apache/poi/poifs/filesystem/POIFSStream.java | 1 +
.../poi/poifs/filesystem/TestPOIFSStream.java | 86 +++++++++++++++++-----
8 files changed, 135 insertions(+), 22 deletions(-)
diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/BlockStore.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/BlockStore.java
index 0484c90117..863376de78 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/BlockStore.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/BlockStore.java
@@ -77,6 +77,16 @@ public abstract class BlockStore {
*/
protected abstract ChainLoopDetector getChainLoopDetector() throws
IOException;
+ /**
+ * Checks that the blocks may be changed, i.e. that changes to them are
kept
+ *
+ * @throws IllegalStateException if the blocks are read-only
+ * @since 6.0.1
+ */
+ protected void checkWriteable() {
+ // writeable by default
+ }
+
/**
* Used to detect if a chain has a loop in it, so
* we can bail out with an error rather than
diff --git
a/poi/src/main/java/org/apache/poi/poifs/filesystem/DirectoryNode.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/DirectoryNode.java
index a2048c3292..3bccb8e284 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/DirectoryNode.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/DirectoryNode.java
@@ -158,6 +158,7 @@ public class DirectoryNode
*/
DocumentEntry createDocument(final POIFSDocument document)
throws IOException {
+ _filesystem.markChanged();
DocumentProperty property = document.getDocumentProperty();
DocumentNode rval = new DocumentNode(property, this);
@@ -179,6 +180,7 @@ public class DirectoryNode
* @return true if the operation succeeded, else false
*/
boolean changeName(final String oldName, final String newName) {
+ _filesystem.markChanged();
boolean rval = false;
EntryNode child = ( EntryNode )
_byUCName.get(oldName.toUpperCase(Locale.ROOT));
@@ -204,6 +206,7 @@ public class DirectoryNode
*/
boolean deleteEntry(final EntryNode entry) {
+ _filesystem.markChanged();
boolean rval =
(( DirectoryProperty ) getProperty())
.deleteChild(entry.getProperty());
@@ -418,6 +421,7 @@ public class DirectoryNode
*/
@Override
public DirectoryEntry createDirectory(final String name) throws
IOException {
+ _filesystem.markChanged();
DirectoryProperty property = new DirectoryProperty(name);
DirectoryNode rval = new DirectoryNode(property, _filesystem, this);
@@ -471,6 +475,7 @@ public class DirectoryNode
*/
@Override
public void setStorageClsid(ClassID clsidStorage) {
+ _filesystem.markChanged();
getProperty().setStorageClsid(clsidStorage);
}
diff --git
a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
index 579266a0bc..5f5de0655a 100644
---
a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
+++
b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
@@ -84,6 +84,8 @@ public final class DocumentOutputStream extends OutputStream {
}
DocumentOutputStream(POIFSDocument document, long limit) throws
IOException {
+ // before the old contents are freed
+ document.getFileSystem().checkWriteable();
_document = document;
_document.free();
@@ -103,6 +105,7 @@ public final class DocumentOutputStream extends
OutputStream {
if (!(parent instanceof DirectoryNode)) {
throw new IOException("Cannot open internal directory storage, " +
parent + " not a Directory Node");
}
+ ((DirectoryNode) parent).getFileSystem().checkWriteable();
// Have an empty one created for now
return parent.createDocument(name,
UnsynchronizedByteArrayInputStream.builder().setByteArray(new byte[0]).get());
diff --git
a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java
index cf8ce464a7..2271bc35a6 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java
@@ -158,6 +158,7 @@ public final class POIFSDocument implements POIFSViewable,
Iterable<ByteBuffer>
* Frees the underlying stream and property
*/
void free() throws IOException {
+ _filesystem.markChanged();
_stream.free();
_property.setStartBlock(POIFSConstants.END_OF_CHAIN);
}
@@ -187,6 +188,8 @@ public final class POIFSDocument implements POIFSViewable,
Iterable<ByteBuffer>
}
public void replaceContents(InputStream stream) throws IOException {
+ // before the old contents are freed
+ _filesystem.checkWriteable();
free();
int size = store(stream);
_property.setStartBlock(_stream.getStartBlock());
diff --git
a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
index e62192f99d..d25f63c325 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
@@ -87,6 +87,8 @@ public class POIFSFileSystem extends BlockStore
private final List<BATBlock> _bat_blocks;
private HeaderBlock _header;
private DirectoryNode _root;
+ // whether the entries were changed, see markChanged()
+ private boolean _changed;
protected DataSource _data;
@@ -758,10 +760,19 @@ public class POIFSFileSystem extends BlockStore
* @param stream the OutputStream to which the filesystem will be
* written
* @throws IOException thrown on errors writing to the stream
+ * @throws IllegalStateException if the filesystem was opened read only
from a file, and its entries were changed
*/
public void writeFilesystem(final OutputStream stream) throws IOException {
- // Have the datasource updated
- syncWithDataSource();
+ // Have the datasource updated - the blocks of a read only file are
+ // copies which wouldn't take the update, so it can only be copied as
it is
+ if (!isReadOnlyFile()) {
+ syncWithDataSource();
+ } else if (_changed) {
+ throw new IllegalStateException(
+ "POIFS opened in read only mode was changed, and the
changes can't be written out. " +
+ "Open the FileSystem in read-write mode, or from
an InputStream, first"
+ );
+ }
// Now copy the contents to the stream
_data.copyTo(stream);
@@ -992,6 +1003,35 @@ public class POIFSFileSystem extends BlockStore
}
}
+ /**
+ * A file opened in read only mode is read into copies of its blocks,
+ * so changes to it would be silently dropped
+ */
+ private boolean isReadOnlyFile() {
+ return (_data instanceof FileBackedDataSource fbds) &&
!fbds.isWriteable();
+ }
+
+ /**
+ * Stream data written to a read only file would be lost straight away
+ */
+ @Override
+ protected void checkWriteable() {
+ if (isReadOnlyFile()) {
+ throw new IllegalStateException(
+ "POIFS opened in read only mode, so stream data may not be
written. " +
+ "Open the FileSystem in read-write mode, or from
an InputStream, first"
+ );
+ }
+ }
+
+ /**
+ * Records a change to the entries, which only lives in memory
+ * if the file was opened in read only mode
+ */
+ void markChanged() {
+ _changed = true;
+ }
+
private static void sanityCheckBlockCount(int block_count) throws
IOException {
if (block_count <= 0) {
throw new IOException(
diff --git
a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSMiniStore.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSMiniStore.java
index 5274361649..e433886a61 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSMiniStore.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSMiniStore.java
@@ -279,4 +279,9 @@ public class POIFSMiniStore extends BlockStore {
protected void releaseBuffer(ByteBuffer buffer) {
_filesystem.releaseBuffer(buffer);
}
+
+ @Override
+ protected void checkWriteable() {
+ _filesystem.checkWriteable();
+ }
}
diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSStream.java
b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSStream.java
index e2a8073356..b58072a32e 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSStream.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSStream.java
@@ -251,6 +251,7 @@ public class POIFSStream implements Iterable<ByteBuffer>
int prevBlock, nextBlock;
StreamBlockByteBuffer() throws IOException {
+ blockStore.checkWriteable();
loopDetector = blockStore.getChainLoopDetector();
prevBlock = POIFSConstants.END_OF_CHAIN;
nextBlock = startBlock;
diff --git
a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
index 646e236cb1..0cf7707e43 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
@@ -21,6 +21,7 @@ import static
org.apache.poi.POIDataSamples.writeOutAndReadBack;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -37,6 +38,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
@@ -2607,28 +2609,15 @@ final class TestPOIFSStream {
*/
@Test
void deletedDataIsNotWrittenOut() throws IOException {
- byte[] data = new byte[10_000];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte)('A' + i % 26);
- }
- byte[] marker = Arrays.copyOf(data, 26);
-
- byte[] original;
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- // big block streams and one in the mini stream
- fs.createDocument(new ByteArrayInputStream(data), "Big");
- fs.createDocument(new ByteArrayInputStream(data), "Replaced");
- fs.createDocument(new ByteArrayInputStream(data, 0, 1_000),
"Small");
- original = writeOut(fs);
- }
- assertTrue(contains(original, marker));
+ byte[] original = createSample();
+ assertTrue(contains(original, MARKER), "the sample contains the
marker");
byte[] modified;
try (POIFSFileSystem fs = new POIFSFileSystem(new
ByteArrayInputStream(original))) {
deleteAndReplace(fs);
modified = writeOut(fs);
}
- assertFalse(contains(modified, marker));
+ assertFalse(contains(modified, MARKER), "deleted data must not be
written out");
try (POIFSFileSystem fs = new POIFSFileSystem(new
ByteArrayInputStream(modified))) {
assertEquals(1, fs.getRoot().getEntryCount());
assertEquals(10,
((DocumentEntry)fs.getRoot().getEntry("Replaced")).getSize());
@@ -2643,15 +2632,72 @@ final class TestPOIFSStream {
fs.writeFilesystem();
}
modified = Files.readAllBytes(file.toPath());
- assertFalse(contains(modified, marker));
+ assertFalse(contains(modified, MARKER), "deleted data must not be
written out in place");
} finally {
- assertTrue(file.delete());
+ Files.deleteIfExists(file.toPath());
+ }
+ }
+
+ /**
+ * A file opened read only is read into copies of its blocks, so stream
data
+ * can't be written to it, and changes to its entries can't be written out
+ */
+ @Test
+ void readOnlyFileChangesAreNotLost() throws IOException {
+ byte[] original = createSample();
+ File file = TempFile.createTempFile("poifs-read-only", ".ole2");
+ try {
+ Files.write(file.toPath(), original);
+ try (POIFSFileSystem fs = new POIFSFileSystem(file, true)) {
+ DirectoryNode root = fs.getRoot();
+ ByteArrayInputStream newData = new ByteArrayInputStream(new
byte[10]);
+ assertThrows(IllegalStateException.class, () ->
fs.createDocument(newData, "New"));
+ assertThrows(IllegalStateException.class, () ->
fs.createOrUpdateDocument(newData, "Replaced"));
+ assertThrows(IllegalStateException.class, () -> new
DocumentOutputStream(root, "Empty"));
+ assertThrows(IllegalStateException.class, () -> new
DocumentOutputStream((DocumentEntry) root.getEntry("Big")));
+
+ // nothing was changed, so the file is written out as it is
+ assertEquals(3, root.getEntryCount());
+ assertArrayEquals(original, writeOut(fs));
+ }
+
+ try (POIFSFileSystem fs = new POIFSFileSystem(file, true)) {
+ // the entries can be changed in memory ...
+ DirectoryNode root = fs.getRoot();
+ assertTrue(root.getEntry("Big").delete(), "Big is deleted");
+ assertTrue(root.getEntry("Small").renameTo("Renamed"), "Small
is renamed");
+ assertEquals(2, root.getEntryCount());
+ assertTrue(root.hasEntry("Renamed"), "Renamed is found");
+
+ // ... but those changes can't be written out
+ assertThrows(IllegalStateException.class, () -> writeOut(fs));
+ }
+ } finally {
+ Files.deleteIfExists(file.toPath());
+ }
+ }
+
+ private static final byte[] MARKER =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.US_ASCII);
+
+ /**
+ * Big block streams and one in the mini stream, all of them repeating
{@link #MARKER}
+ */
+ private static byte[] createSample() throws IOException {
+ byte[] data = new byte[10_000];
+ for (int i = 0; i < data.length; i++) {
+ data[i] = MARKER[i % MARKER.length];
+ }
+ try (POIFSFileSystem fs = new POIFSFileSystem()) {
+ fs.createDocument(new ByteArrayInputStream(data), "Big");
+ fs.createDocument(new ByteArrayInputStream(data), "Replaced");
+ fs.createDocument(new ByteArrayInputStream(data, 0, 1_000),
"Small");
+ return writeOut(fs);
}
}
private static void deleteAndReplace(POIFSFileSystem fs) throws
IOException {
- assertTrue(fs.getRoot().getEntry("Big").delete());
- assertTrue(fs.getRoot().getEntry("Small").delete());
+ assertTrue(fs.getRoot().getEntry("Big").delete(), "Big is deleted");
+ assertTrue(fs.getRoot().getEntry("Small").delete(), "Small is
deleted");
fs.createOrUpdateDocument(new ByteArrayInputStream(new byte[10]),
"Replaced");
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]