This is an automated email from the ASF dual-hosted git repository.

chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-mime4j.git

commit ffa0dbd2f52695222b0bd53e4d5f316e0a42ef6e
Author: Benoit TELLIER <[email protected]>
AuthorDate: Tue Nov 10 10:52:26 2026 +0100

    [FIX] BasicBodyFactory: a disposed body no longer reaches its recycled 
buffer
    
    StringBody3 and BinaryBody3 hand their buffer back to the per-thread
    ByteArrayOutputStreamRecycler on dispose() but kept using it: the next
    body buffered on that thread, often the next message and another user's
    mail, took the same UnsynchronizedByteArrayOutputStream, and from then on
    getInputStream, getReader, writeTo and size of the disposed body returned
    that other content without error. copy() after dispose() brought the
    released buffer back to a count of 1, so the copy and the next owner
    shared one buffer.
    
    A disposed body now drops its buffer and throws IllegalStateException
    ("body has been disposed") from these methods and from copy(), as
    TempFileStorage already does. ByteArrayOutputStreamRecycler.Wrapper refuses
    retain() and getValue() once released, and a second release no longer
    counts below 0. The other recycled holders drop their arrays on release
    too: RecycledByteArrayBuffer falls back to plain arrays if it is still
    appended to (a field read after stop() wrote into the recycled array), and
    BufferedLineReaderInputStream reads nothing more. Streams opened before
    dispose() keep their content.
---
 .../mime4j/io/BufferedLineReaderInputStream.java   |  9 +++
 .../mime4j/util/ByteArrayOutputStreamRecycler.java | 35 ++++++++--
 .../james/mime4j/util/RecycledByteArrayBuffer.java | 11 +++
 .../mime4j/util/RecycledBufferReleaseTest.java     | 80 ++++++++++++++++++++++
 .../james/mime4j/message/BasicBodyFactory.java     | 54 ++++++++++-----
 .../mime4j/message/BasicBodyFactoryCopyTest.java   | 68 ++++++++++++++++++
 6 files changed, 234 insertions(+), 23 deletions(-)

diff --git 
a/core/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
 
b/core/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
index f43c0f02..96aaad8e 100644
--- 
a/core/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
+++ 
b/core/src/main/java/org/apache/james/mime4j/io/BufferedLineReaderInputStream.java
@@ -46,6 +46,8 @@ public class BufferedLineReaderInputStream extends 
LineReaderInputStream {
         return br;
     }
 
+    private static final byte[] EMPTY_BYTES = new byte[0];
+
     private boolean truncated;
     private boolean released;
 
@@ -145,6 +147,13 @@ public class BufferedLineReaderInputStream extends 
LineReaderInputStream {
         BufferRecycler bufferRecycler = getBufferRecycler();
         bufferRecycler.releaseByteBuffer(0, buffer);
         bufferRecycler.releaseIntBuffer(shiftTable);
+        // The arrays may now be handed to another stream: never read nor 
write them again
+        this.buffer = EMPTY_BYTES;
+        this.shiftTable = new int[256];
+        this.cachedShiftPattern = null;
+        this.bufpos = 0;
+        this.buflen = 0;
+        this.truncated = true;
     }
 
     protected boolean readAllowed() {
diff --git 
a/core/src/main/java/org/apache/james/mime4j/util/ByteArrayOutputStreamRecycler.java
 
b/core/src/main/java/org/apache/james/mime4j/util/ByteArrayOutputStreamRecycler.java
index d000f18d..d7c57c56 100644
--- 
a/core/src/main/java/org/apache/james/mime4j/util/ByteArrayOutputStreamRecycler.java
+++ 
b/core/src/main/java/org/apache/james/mime4j/util/ByteArrayOutputStreamRecycler.java
@@ -46,19 +46,46 @@ public class ByteArrayOutputStreamRecycler {
         /**
          * Registers an additional owner of the underlying buffer, which then 
needs one more
          * {@link #release()} before being recycled.
+         *
+         * @throws IllegalStateException if the buffer has already been 
released: it may already
+         *   be in use by another owner
          */
         public Wrapper retain() {
-            REFERENCES.incrementAndGet(this);
-            return this;
+            for (;;) {
+                int current = references;
+                if (current <= 0) {
+                    throw new IllegalStateException("buffer has been 
released");
+                }
+                if (REFERENCES.compareAndSet(this, current, current + 1)) {
+                    return this;
+                }
+            }
         }
 
         public void release() {
-            if (REFERENCES.decrementAndGet(this) == 0) {
-                recycler.release(value);
+            for (;;) {
+                int current = references;
+                if (current <= 0) {
+                    // Already recycled: recycling it twice would hand it to 
two later owners
+                    return;
+                }
+                if (REFERENCES.compareAndSet(this, current, current - 1)) {
+                    if (current == 1) {
+                        recycler.release(value);
+                    }
+                    return;
+                }
             }
         }
 
+        /**
+         * @throws IllegalStateException if the buffer has been released: it 
may then hold the
+         *   content of another owner
+         */
         public UnsynchronizedByteArrayOutputStream getValue() {
+            if (references <= 0) {
+                throw new IllegalStateException("buffer has been released");
+            }
             return value;
         }
     }
diff --git 
a/core/src/main/java/org/apache/james/mime4j/util/RecycledByteArrayBuffer.java 
b/core/src/main/java/org/apache/james/mime4j/util/RecycledByteArrayBuffer.java
index e355bb21..13d289f4 100644
--- 
a/core/src/main/java/org/apache/james/mime4j/util/RecycledByteArrayBuffer.java
+++ 
b/core/src/main/java/org/apache/james/mime4j/util/RecycledByteArrayBuffer.java
@@ -25,6 +25,7 @@ import java.nio.charset.StandardCharsets;
  * A resizable byte array.
  */
 public final class RecycledByteArrayBuffer implements ByteSequence {
+    private static final byte[] EMPTY = new byte[0];
     private final BufferRecycler bufferRecycler;
     private byte[] buffer;
     private int len;
@@ -60,6 +61,13 @@ public final class RecycledByteArrayBuffer implements 
ByteSequence {
     }
 
     private void expand(int newlen) {
+        if (released) {
+            // Still used after release (e.g. a field read after stop()): 
plain arrays from now on
+            byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, 
newlen)];
+            System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
+            this.buffer = newbuffer;
+            return;
+        }
         byte newbuffer[] = bufferRecycler.allocByteBuffer(0, 
Math.max(this.buffer.length << 1, newlen));
         System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
         bufferRecycler.releaseByteBuffer(0, buffer);
@@ -187,6 +195,9 @@ public final class RecycledByteArrayBuffer implements 
ByteSequence {
         if (!released) {
             released = true;
             bufferRecycler.releaseByteBuffer(0, buffer);
+            // The array may now be handed to another user: never read nor 
write it again
+            this.buffer = EMPTY;
+            this.len = 0;
         }
     }
 
diff --git 
a/core/src/test/java/org/apache/james/mime4j/util/RecycledBufferReleaseTest.java
 
b/core/src/test/java/org/apache/james/mime4j/util/RecycledBufferReleaseTest.java
new file mode 100644
index 00000000..2e637b9d
--- /dev/null
+++ 
b/core/src/test/java/org/apache/james/mime4j/util/RecycledBufferReleaseTest.java
@@ -0,0 +1,80 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.james.mime4j.util;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * A released recycled buffer is never reached again through its former owner.
+ */
+public class RecycledBufferReleaseTest {
+
+    @Test
+    public void retainAfterTheLastReleaseShouldBeRefused() {
+        ByteArrayOutputStreamRecycler recycler = new 
ByteArrayOutputStreamRecycler();
+        ByteArrayOutputStreamRecycler.Wrapper wrapper = 
recycler.allocOutputStream();
+        wrapper.release();
+        try {
+            wrapper.retain();
+            Assert.fail("Expected IllegalStateException");
+        } catch (IllegalStateException expected) {
+            // expected
+        }
+    }
+
+    @Test
+    public void getValueAfterTheLastReleaseShouldBeRefused() {
+        ByteArrayOutputStreamRecycler recycler = new 
ByteArrayOutputStreamRecycler();
+        ByteArrayOutputStreamRecycler.Wrapper wrapper = 
recycler.allocOutputStream();
+        wrapper.retain();
+        wrapper.release();
+        Assert.assertNotNull(wrapper.getValue());
+        wrapper.release();
+        try {
+            wrapper.getValue();
+            Assert.fail("Expected IllegalStateException");
+        } catch (IllegalStateException expected) {
+            // expected
+        }
+    }
+
+    @Test
+    public void releasingTwiceShouldRecycleTheBufferOnce() {
+        ByteArrayOutputStreamRecycler recycler = new 
ByteArrayOutputStreamRecycler();
+        ByteArrayOutputStreamRecycler.Wrapper wrapper = 
recycler.allocOutputStream();
+        wrapper.release();
+        wrapper.release();
+        Assert.assertTrue(recycler.buffers.size() <= 1);
+    }
+
+    @Test
+    public void aReleasedByteArrayBufferShouldNotWriteIntoTheRecycledArray() {
+        BufferRecycler recycler = new BufferRecycler();
+        RecycledByteArrayBuffer buffer = new RecycledByteArrayBuffer(recycler, 
16);
+        byte[] recycled = buffer.buffer();
+        buffer.release();
+        buffer.append(new byte[] {'a', 'b'}, 0, 2);
+
+        Assert.assertNotSame(recycled, buffer.buffer());
+        Assert.assertEquals("ab", buffer.toString());
+        Assert.assertEquals(0, recycled[0]);
+    }
+}
diff --git 
a/dom/src/main/java/org/apache/james/mime4j/message/BasicBodyFactory.java 
b/dom/src/main/java/org/apache/james/mime4j/message/BasicBodyFactory.java
index 4c14ebf5..2409657f 100644
--- a/dom/src/main/java/org/apache/james/mime4j/message/BasicBodyFactory.java
+++ b/dom/src/main/java/org/apache/james/mime4j/message/BasicBodyFactory.java
@@ -248,9 +248,9 @@ public class BasicBodyFactory implements BodyFactory {
 
     static class StringBody3 extends TextBody {
 
-        private final ByteArrayOutputStreamRecycler.Wrapper content;
+        // null once disposed: the buffer may then be recycled for another body
+        private ByteArrayOutputStreamRecycler.Wrapper content;
         private final Charset charset;
-        private boolean disposed;
 
         StringBody3(final ByteArrayOutputStreamRecycler.Wrapper content, final 
Charset charset) {
             super();
@@ -258,6 +258,13 @@ public class BasicBodyFactory implements BodyFactory {
             this.charset = charset;
         }
 
+        private ByteArrayOutputStreamRecycler.Wrapper content() {
+            if (content == null) {
+                throw new IllegalStateException("body has been disposed");
+            }
+            return content;
+        }
+
         @Override
         public String getMimeCharset() {
             return this.charset != null ? this.charset.name() : null;
@@ -270,35 +277,36 @@ public class BasicBodyFactory implements BodyFactory {
 
         @Override
         public Reader getReader() throws IOException {
-            return new 
InputStreamReader(this.content.getValue().toInputStream(), this.charset);
+            return new InputStreamReader(content().getValue().toInputStream(), 
this.charset);
         }
 
         @Override
         public InputStream getInputStream() throws IOException {
-            return this.content.getValue().toInputStream();
+            return content().getValue().toInputStream();
         }
 
         @Override
         public long size() {
-            return content.getValue().size();
+            return content().getValue().size();
         }
 
         @Override
         public void writeTo(OutputStream out) throws IOException {
-            content.getValue().writeTo(out);
+            content().getValue().writeTo(out);
         }
 
         @Override
         public void dispose() {
-            if (!disposed) {
-                disposed = true;
-                this.content.release();
+            if (content != null) {
+                ByteArrayOutputStreamRecycler.Wrapper released = content;
+                content = null;
+                released.release();
             }
         }
 
         @Override
         public SingleBody copy() {
-            return new StringBody3(this.content.retain(), this.charset);
+            return new StringBody3(content().retain(), this.charset);
         }
 
     }
@@ -340,40 +348,48 @@ public class BasicBodyFactory implements BodyFactory {
 
     static class BinaryBody3 extends BinaryBody {
 
-        private final ByteArrayOutputStreamRecycler.Wrapper content;
-        private boolean disposed;
+        // null once disposed: the buffer may then be recycled for another body
+        private ByteArrayOutputStreamRecycler.Wrapper content;
 
         BinaryBody3(ByteArrayOutputStreamRecycler.Wrapper content) {
             super();
             this.content = content;
         }
 
+        private ByteArrayOutputStreamRecycler.Wrapper content() {
+            if (content == null) {
+                throw new IllegalStateException("body has been disposed");
+            }
+            return content;
+        }
+
         @Override
         public InputStream getInputStream() throws IOException {
-            return content.getValue().toInputStream();
+            return content().getValue().toInputStream();
         }
 
         @Override
         public void writeTo(OutputStream out) throws IOException {
-            content.getValue().writeTo(out);
+            content().getValue().writeTo(out);
         }
 
         @Override
         public long size() {
-            return content.getValue().size();
+            return content().getValue().size();
         }
 
         @Override
         public void dispose() {
-            if (!disposed) {
-                disposed = true;
-                content.release();
+            if (content != null) {
+                ByteArrayOutputStreamRecycler.Wrapper released = content;
+                content = null;
+                released.release();
             }
         }
 
         @Override
         public SingleBody copy() {
-            return new BinaryBody3(content.retain());
+            return new BinaryBody3(content().retain());
         }
 
     }
diff --git 
a/dom/src/test/java/org/apache/james/mime4j/message/BasicBodyFactoryCopyTest.java
 
b/dom/src/test/java/org/apache/james/mime4j/message/BasicBodyFactoryCopyTest.java
index ccc9e6b7..fcb706b4 100644
--- 
a/dom/src/test/java/org/apache/james/mime4j/message/BasicBodyFactoryCopyTest.java
+++ 
b/dom/src/test/java/org/apache/james/mime4j/message/BasicBodyFactoryCopyTest.java
@@ -21,10 +21,12 @@ package org.apache.james.mime4j.message;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
 
 import org.apache.james.mime4j.dom.Message;
 import org.apache.james.mime4j.dom.SingleBody;
+import org.apache.james.mime4j.dom.TextBody;
 import org.junit.Assert;
 import org.junit.Test;
 
@@ -87,4 +89,70 @@ public class BasicBodyFactoryCopyTest {
         Assert.assertEquals("first\r\n", body(first));
         Assert.assertEquals("second\r\n", body(second));
     }
+
+    private interface BodyAccess {
+        void run(SingleBody body) throws Exception;
+    }
+
+    private static void assertDisposed(SingleBody body, BodyAccess access) 
throws Exception {
+        try {
+            access.run(body);
+            Assert.fail("Expected IllegalStateException");
+        } catch (IllegalStateException expected) {
+            // the body no longer reaches its recycled buffer
+        }
+    }
+
+    private static void assertDisposedBodyDoesNotServeTheNextMessage(String 
contentType) throws Exception {
+        Message original = parse("Content-Type: " + contentType + 
"\r\n\r\nhello\r\n");
+        SingleBody body = (SingleBody) original.getBody();
+        original.dispose();
+        Message other = parse("Content-Type: " + contentType + 
"\r\n\r\nsomeone else's mail\r\n");
+
+        assertDisposed(body, b -> b.getInputStream());
+        assertDisposed(body, b -> b.writeTo(new ByteArrayOutputStream()));
+        assertDisposed(body, b -> b.size());
+        assertDisposed(body, b -> b.copy());
+        if (body instanceof TextBody) {
+            assertDisposed(body, b -> ((TextBody) b).getReader());
+        }
+        Assert.assertEquals("someone else's mail\r\n", body(other));
+    }
+
+    @Test
+    public void aDisposedTextBodyShouldNotServeTheNextMessage() throws 
Exception {
+        assertDisposedBodyDoesNotServeTheNextMessage("text/plain");
+    }
+
+    @Test
+    public void aDisposedBinaryBodyShouldNotServeTheNextMessage() throws 
Exception {
+        
assertDisposedBodyDoesNotServeTheNextMessage("application/octet-stream");
+    }
+
+    @Test
+    public void copyAfterDisposeShouldNotShareTheNextMessageBuffer() throws 
Exception {
+        Message original = parse("Content-Type: text/plain\r\n\r\nhello\r\n");
+        SingleBody body = (SingleBody) original.getBody();
+        original.dispose();
+
+        assertDisposed(body, b -> b.copy());
+        Message other = parse("Content-Type: text/plain\r\n\r\nsomeone else's 
mail\r\n");
+        Assert.assertEquals("someone else's mail\r\n", body(other));
+    }
+
+    @Test
+    public void aStreamOpenedBeforeDisposeShouldKeepItsContent() throws 
Exception {
+        Message original = parse("Content-Type: text/plain\r\n\r\nhello\r\n");
+        InputStream in = ((SingleBody) original.getBody()).getInputStream();
+        original.dispose();
+        parse("Content-Type: text/plain\r\n\r\nsomeone else's mail\r\n");
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        byte[] buf = new byte[64];
+        int n;
+        while ((n = in.read(buf)) != -1) {
+            out.write(buf, 0, n);
+        }
+        Assert.assertEquals("hello\r\n", out.toString("US-ASCII"));
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to