This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch mina-2.2.X
in repository https://gitbox.apache.org/repos/asf/mina.git
The following commit(s) were added to refs/heads/mina-2.2.X by this push:
new edef90349 Limit the number of read messages to avoid exhausting the
reading queue
edef90349 is described below
commit edef90349f80e635306ee29d2db61a3da2d80ac6
Author: emmanuel lecharny <[email protected]>
AuthorDate: Tue Nov 24 10:36:51 2026 +0100
Limit the number of read messages to avoid exhausting the reading queue
---
.../mina/core/session/AbstractIoSession.java | 75 ++++++++++++-
.../handlers/http/AbstractHttpLogicHandler.java | 13 ++-
.../AbstractIoSessionReadFutureLimitTest.java | 73 +++++++++++++
.../handlers/HttpConnectHandshakeStatusTest.java | 119 +++++++++++++++++++++
4 files changed, 275 insertions(+), 5 deletions(-)
diff --git
a/mina-core/src/main/java/org/apache/mina/core/session/AbstractIoSession.java
b/mina-core/src/main/java/org/apache/mina/core/session/AbstractIoSession.java
index 4f1d4c6f8..9a3d7417d 100644
---
a/mina-core/src/main/java/org/apache/mina/core/session/AbstractIoSession.java
+++
b/mina-core/src/main/java/org/apache/mina/core/session/AbstractIoSession.java
@@ -78,6 +78,28 @@ public abstract class AbstractIoSession implements IoSession
{
private static final AttributeKey WAITING_READ_FUTURES_KEY = new
AttributeKey(AbstractIoSession.class,
"waitingReadFutures");
+ /**
+ * The default maximum number of received messages queued as ready
+ * {@link ReadFuture}s when {@link IoSessionConfig#isUseReadOperation()}
+ * is enabled. Without a bound, a peer sending faster than the
+ * application calls {@link #read()} would make the queue - and the
+ * peer-supplied messages it retains - grow without limit until the heap
+ * is exhausted. When the limit is reached, the session's read interest
+ * is suspended until the application drains the queue below half of the
+ * limit. It can be changed globally with the
+ * <tt>org.apache.mina.session.maxQueuedReadFutures</tt> system property,
+ * or per session with {@link #setMaxQueuedReadFutures(int)}. A value of
+ * <tt>0</tt> or less disables the limit (previous, unbounded behavior).
+ */
+ public static final int DEFAULT_MAX_QUEUED_READ_FUTURES =
Integer.getInteger(
+ "org.apache.mina.session.maxQueuedReadFutures", 512);
+
+ /** The maximum number of ready ReadFutures queued for this session */
+ private volatile int maxQueuedReadFutures =
DEFAULT_MAX_QUEUED_READ_FUTURES;
+
+ /** Set to true when reads were suspended because the ready ReadFutures
queue hit its limit */
+ private volatile boolean readSuspendedByReadFutureLimit;
+
private static final IoFutureListener<CloseFuture>
SCHEDULED_COUNTER_RESETTER = new IoFutureListener<CloseFuture>() {
public void operationComplete(CloseFuture future) {
AbstractIoSession session = (AbstractIoSession)
future.getSession();
@@ -422,8 +444,45 @@ public abstract class AbstractIoSession implements
IoSession {
}
}
+ // The application is draining the queue: resume reading once it went
+ // below half of the configured limit.
+ if (readSuspendedByReadFutureLimit) {
+ int max = maxQueuedReadFutures;
+
+ if ((max <= 0) || (readyReadFutures.size() <= max / 2)) {
+ readSuspendedByReadFutureLimit = false;
+ resumeRead();
+ }
+ }
+
+
return future;
}
+
+ /**
+ * @return the maximum number of received messages queued as ready
+ * {@link ReadFuture}s when {@link IoSessionConfig#isUseReadOperation()}
+ * is enabled, before the session's read interest is suspended.
+ * A value of <tt>0</tt> or less means no limit.
+ */
+ public final int getMaxQueuedReadFutures() {
+ return maxQueuedReadFutures;
+ }
+
+ /**
+ * Sets the maximum number of received messages queued as ready
+ * {@link ReadFuture}s when {@link IoSessionConfig#isUseReadOperation()}
+ * is enabled. When the limit is reached, the session's read interest is
+ * suspended until {@link #read()} drains the queue below half of the
+ * limit, so a peer sending faster than the application reads cannot
+ * exhaust the heap. Defaults to {@link #DEFAULT_MAX_QUEUED_READ_FUTURES}.
+ *
+ * @param maxQueuedReadFutures the limit; a value of <tt>0</tt> or less
+ * disables it (unbounded queue)
+ */
+ public final void setMaxQueuedReadFutures(int maxQueuedReadFutures) {
+ this.maxQueuedReadFutures = maxQueuedReadFutures;
+ }
/**
* Associates a message to a ReadFuture
@@ -462,16 +521,28 @@ public abstract class AbstractIoSession implements
IoSession {
Queue<ReadFuture> readyReadFutures = getReadyReadFutures();
Queue<ReadFuture> waitingReadFutures = getWaitingReadFutures();
ReadFuture future;
-
+
+ boolean limitReached = false;
+
synchronized (readyReadFutures) {
future = waitingReadFutures.poll();
if (future == null) {
future = new DefaultReadFuture(this);
readyReadFutures.offer(future);
+ int max = maxQueuedReadFutures;
+ limitReached = (max > 0) && (readyReadFutures.size() >= max);
}
}
-
+
+ // Stop reading from the peer until the application drains the queued
+ // ReadFutures: they retain every received message, so letting the
+ // queue grow unchecked hands the peer an unbounded heap allocation.
+ if (limitReached && !readSuspendedByReadFutureLimit) {
+ readSuspendedByReadFutureLimit = true;
+ suspendRead();
+ }
+
return future;
}
diff --git
a/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
b/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
index b293491f9..960401767 100644
---
a/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
+++
b/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
@@ -160,9 +160,16 @@ public abstract class AbstractHttpLogicHandler extends
AbstractProxyLogicHandler
parsedResponse = decodeResponse(responseHeader);
// Is handshake complete ?
- if (parsedResponse.getStatusCode() == 200
- || (parsedResponse.getStatusCode() >= 300 &&
parsedResponse.getStatusCode() <= 307)) {
- buf.position(0);
+ // Only a successful response establishes the tunnel. A 3xx
+ // answer to a CONNECT request is a redirect/failure (RFC
9110):
+ // the proxy did NOT switch to tunnel mode, so it must be
+ // handled as an error below, never as an established tunnel.
+ if (parsedResponse.getStatusCode() == 200) {
+ // Leave the buffer positioned right after the consumed
+ // handshake bytes so that only genuine post-tunnel data is
+ // forwarded to the next filter; rewinding to 0 would
replay
+ // the already-consumed proxy response into the
+ // application's decoder chain.
setHandshakeComplete();
return;
}
diff --git
a/mina-core/src/test/java/org/apache/mina/core/session/AbstractIoSessionReadFutureLimitTest.java
b/mina-core/src/test/java/org/apache/mina/core/session/AbstractIoSessionReadFutureLimitTest.java
new file mode 100644
index 000000000..55af37a32
--- /dev/null
+++
b/mina-core/src/test/java/org/apache/mina/core/session/AbstractIoSessionReadFutureLimitTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.mina.core.session;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * Tests that the ready {@link org.apache.mina.core.future.ReadFuture} queue
+ * used when <tt>useReadOperation</tt> is enabled is bounded: when the
+ * application does not drain {@link AbstractIoSession#read()} fast enough,
+ * the session must suspend reads instead of queueing every received message
+ * until the heap is exhausted.
+ *
+ * @author <a href="http://mina.apache.org">Apache MINA Project</a>
+ */
+public class AbstractIoSessionReadFutureLimitTest {
+ @Test
+ public void testReadFutureQueueIsBoundedByDefault() {
+ DummySession session = new DummySession();
+ assertEquals(AbstractIoSession.DEFAULT_MAX_QUEUED_READ_FUTURES,
session.getMaxQueuedReadFutures());
+ assertTrue(session.getMaxQueuedReadFutures() > 0);
+ }
+
+ @Test
+ public void testReachingTheLimitSuspendsReadsAndDrainingResumesThem()
throws Exception {
+ DummySession session = new DummySession();
+ session.getConfig().setUseReadOperation(true);
+ session.setMaxQueuedReadFutures(4);
+
+ for (int i = 0; i < 4; i++) {
+ assertFalse(session.isReadSuspended());
+ session.offerReadFuture(Integer.valueOf(i));
+ }
+
+ // The limit was reached: read interest must have been suspended
+ assertTrue(session.isReadSuspended());
+
+ // Messages already in flight are still queued, and reads stay
suspended
+ session.offerReadFuture(Integer.valueOf(4));
+ assertTrue(session.isReadSuspended());
+
+ // Draining below half of the limit resumes reads
+ assertEquals(0, session.read().getMessage());
+ assertEquals(1, session.read().getMessage());
+ assertTrue(session.isReadSuspended());
+ assertEquals(2, session.read().getMessage());
+ assertFalse(session.isReadSuspended());
+
+ assertEquals(3, session.read().getMessage());
+ assertEquals(4, session.read().getMessage());
+ }
+}
diff --git
a/mina-core/src/test/java/org/apache/mina/proxy/handlers/HttpConnectHandshakeStatusTest.java
b/mina-core/src/test/java/org/apache/mina/proxy/handlers/HttpConnectHandshakeStatusTest.java
new file mode 100644
index 000000000..c115847cc
--- /dev/null
+++
b/mina-core/src/test/java/org/apache/mina/proxy/handlers/HttpConnectHandshakeStatusTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.mina.proxy.handlers;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.net.InetSocketAddress;
+
+import org.apache.mina.core.buffer.IoBuffer;
+import org.apache.mina.core.filterchain.IoFilter.NextFilter;
+import org.apache.mina.core.session.DummySession;
+import org.apache.mina.proxy.ProxyAuthException;
+import org.apache.mina.proxy.handlers.http.AbstractHttpLogicHandler;
+import org.apache.mina.proxy.handlers.http.HttpProxyRequest;
+import org.apache.mina.proxy.handlers.http.HttpProxyResponse;
+import org.apache.mina.proxy.session.ProxyIoSession;
+import org.junit.Test;
+
+/**
+ * Regression tests for the HTTP CONNECT handshake status handling:
+ * <ul>
+ * <li>a 3xx response is a redirect/failure and must never be treated as an
+ * established tunnel (previously it completed the handshake and the queued
+ * application data was flushed to the proxy's HTTP front-end),</li>
+ * <li>on success the receive buffer must stay positioned after the consumed
+ * handshake bytes instead of being rewound to 0, which replayed the proxy
+ * response into the application's decoder chain.</li>
+ * </ul>
+ */
+public class HttpConnectHandshakeStatusTest {
+
+ /**
+ * Minimal concrete handler that records the responses routed to
+ * {@link #handleResponse(HttpProxyResponse)}.
+ */
+ private static class TestLogicHandler extends AbstractHttpLogicHandler {
+ HttpProxyResponse lastResponse;
+
+ TestLogicHandler(ProxyIoSession proxyIoSession) {
+ super(proxyIoSession);
+ }
+
+ @Override
+ public void doHandshake(NextFilter nextFilter) throws
ProxyAuthException {
+ // no-op for the test
+ }
+
+ @Override
+ public void handleResponse(HttpProxyResponse response) throws
ProxyAuthException {
+ lastResponse = response;
+ }
+ }
+
+ private static TestLogicHandler createHandler() {
+ ProxyIoSession proxyIoSession = new ProxyIoSession(new
InetSocketAddress("127.0.0.1", 8080),
+ new HttpProxyRequest("host.example:443"));
+ proxyIoSession.setSession(new DummySession());
+
+ return new TestLogicHandler(proxyIoSession);
+ }
+
+ private static IoBuffer wrap(String data) throws Exception {
+ return IoBuffer.wrap(data.getBytes("ISO-8859-1"));
+ }
+
+ @Test
+ public void redirectResponseDoesNotEstablishTunnel() throws Exception {
+ TestLogicHandler handler = createHandler();
+
+ IoBuffer buf = wrap("HTTP/1.0 302 Found\r\nLocation:
http://portal.example/\r\n\r\n");
+ handler.messageReceived(null, buf);
+
+ assertFalse("a 3xx CONNECT response must not complete the handshake",
handler.isHandshakeComplete());
+ assertNotNull("the 3xx response must be routed to handleResponse()",
handler.lastResponse);
+ assertEquals(302, handler.lastResponse.getStatusCode());
+ }
+
+ @Test
+ public void successfulResponseLeavesBufferAfterHandshakeBytes() throws
Exception {
+ TestLogicHandler handler = createHandler();
+
+ String response = "HTTP/1.0 200 Connection established\r\n\r\n";
+ IoBuffer buf = wrap(response + "TUNNELED");
+
+ try {
+ handler.messageReceived(null, buf);
+ } catch (ProxyAuthException e) {
+ // The unit-test ProxyIoSession has no connector wired, so the
+ // handshake-complete notification fails after the buffer has been
+ // positioned; only the buffer state matters here.
+ }
+
+ assertTrue(handler.isHandshakeComplete());
+ assertEquals("the buffer must be positioned after the consumed
handshake bytes", response.length(),
+ buf.position());
+ assertEquals("only genuine post-tunnel data may remain", "TUNNELED",
+
buf.getString(java.nio.charset.StandardCharsets.ISO_8859_1.newDecoder()));
+ }
+}