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

dakirily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/qpid-broker-j.git


The following commit(s) were added to refs/heads/main by this push:
     new 8474439e70 QPID-8791: [Broker-J] An incomplete inbound TLS record can 
cause repeated rescheduling (#466)
8474439e70 is described below

commit 8474439e707e1d0ceb436ca903b0f7be9c8a0032
Author: Kato Kaito <[email protected]>
AuthorDate: Wed Nov 18 11:02:02 2026 +0100

    QPID-8791: [Broker-J] An incomplete inbound TLS record can cause repeated 
rescheduling (#466)
---
 .../NonBlockingConnectionTLSDelegate.java          |   5 +-
 .../NonBlockingConnectionSchedulingTest.java       | 111 +++++++++++++++-
 .../transport/NonBlockingConnectionTLSTest.java    | 141 +++++++++++++++++++--
 .../apache/qpid/server/transport/TlsTestPeer.java  | 113 +++++++++++++++++
 4 files changed, 356 insertions(+), 14 deletions(-)

diff --git 
a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
 
b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
index 8175552aac..4641d245a5 100644
--- 
a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
+++ 
b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
@@ -60,6 +60,7 @@ public class NonBlockingConnectionTLSDelegate implements 
NonBlockingConnectionDe
     private boolean _principalChecked;
     private volatile boolean _hostChecked;
     private volatile boolean _needsReadForWrite;
+    private boolean _needsMoreNetworkData;
     private QpidByteBuffer _netInputBuffer;
     private QpidByteBuffer _netOutputBuffer;
     private QpidByteBuffer _applicationBuffer;
@@ -117,6 +118,7 @@ public class NonBlockingConnectionTLSDelegate implements 
NonBlockingConnectionDe
                 }
                 else
                 {
+                    _needsMoreNetworkData = true;
                     return false;
                 }
             }
@@ -131,6 +133,7 @@ public class NonBlockingConnectionTLSDelegate implements 
NonBlockingConnectionDe
             oldNetBufferPos = _netInputBuffer.position();
 
             _status = QpidByteBuffer.decryptSSL(_sslEngine, _netInputBuffer, 
_applicationBuffer);
+            _needsMoreNetworkData = _status.getStatus() == 
SSLEngineResult.Status.BUFFER_UNDERFLOW;
             if (_status.getStatus() == SSLEngineResult.Status.CLOSED)
             {
                 int remaining = _netInputBuffer.remaining();
@@ -397,7 +400,7 @@ public class NonBlockingConnectionTLSDelegate implements 
NonBlockingConnectionDe
     @Override
     public boolean needsWork()
     {
-        return _sslEngine.getHandshakeStatus() != 
SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
+        return !_needsMoreNetworkData && _sslEngine.getHandshakeStatus() != 
SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
     }
 
     private synchronized void checkPeerPrincipal()
diff --git 
a/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionSchedulingTest.java
 
b/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionSchedulingTest.java
index e12e5a5964..2a3542b895 100644
--- 
a/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionSchedulingTest.java
+++ 
b/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionSchedulingTest.java
@@ -21,6 +21,7 @@ package org.apache.qpid.server.transport;
 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;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
@@ -30,6 +31,7 @@ import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import java.io.IOException;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.Socket;
@@ -73,6 +75,8 @@ import org.apache.qpid.test.utils.UnitTestBase;
 class NonBlockingConnectionSchedulingTest extends UnitTestBase
 {
     private static final int TIMEOUT_MILLIS = 10000;
+    private static final int NETWORK_BUFFER_SIZE = 64 * 1024;
+    private static final int BUFFER_SIZE = 4096;
 
     private final List<Thread> _threads = new CopyOnWriteArrayList<>();
     private final List<TestConnection> _connections = new ArrayList<>();
@@ -190,6 +194,75 @@ class NonBlockingConnectionSchedulingTest extends 
UnitTestBase
         assertTrue(blocked._readerIdle.get(), "The read timeout must still 
close the connection after heartbeats stop");
     }
 
+    @ParameterizedTest
+    @CsvSource({"TLSv1.2, 2", "TLSv1.2, 4", "TLSv1.3, 2", "TLSv1.3, 4"})
+    void incompleteTlsRecordReturnsToSelectorAndResumesOnReadiness(final 
String protocol,
+                                                                   final int 
workers) throws Exception
+    {
+        startScheduler(workers);
+        final TestConnection connection = createTlsEngineConnection();
+        final TlsTestPeer peer = new TlsTestPeer(_sslContext, protocol, 
connection._client);
+        peer.send(peer.wrap(new byte[]{42}));
+        assertEquals(Integer.valueOf(42), 
connection._received.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
+        connection.awaitSelection(false);
+        final TestConnection independent = createConnection(1024);
+
+        for (int round = 0; round < 3; round++)
+        {
+            final byte[] record = peer.wrap(new byte[]{11, 22, 33});
+            final int prefix = record.length - 1;
+            final long expectedRead = connection._networkBytesRead.get() + 
prefix;
+            peer.send(Arrays.copyOf(record, prefix));
+            connection.awaitNetworkBytes(expectedRead);
+
+            connection.awaitSelection(false);
+            assertTrue(connection._connection.wantsRead());
+            assertTrue(connection._received.isEmpty(), "An incomplete record 
must not expose plaintext");
+            independent.submit(List.of(() -> independent.send(new 
byte[]{44})));
+            assertEquals(44, independent._client.getInputStream().read());
+            connection.awaitSelection(false);
+
+            peer.send(Arrays.copyOfRange(record, prefix, record.length));
+            for (int expected : new int[]{11, 22, 33})
+            {
+                assertEquals(Integer.valueOf(expected), 
connection._received.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS),
+                        "Read readiness must resume the buffered record in 
order");
+            }
+            connection.awaitSelection(false);
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"TLSv1.2", "TLSv1.3"})
+    void incompleteTlsRecordStillHonorsReadIdleTimeout(final String protocol) 
throws Exception
+    {
+        startScheduler(2);
+        final TestConnection connection = createTlsEngineConnection();
+        final TlsTestPeer peer = new TlsTestPeer(_sslContext, protocol, 
connection._client);
+        peer.send(peer.wrap(new byte[]{42}));
+        assertEquals(Integer.valueOf(42), 
connection._received.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
+        connection.awaitSelection(false);
+        final long expectedRead = connection._networkBytesRead.get() + 5;
+        peer.send(Arrays.copyOf(peer.wrap(new byte[]{1, 2, 3}), 5));
+        connection.awaitNetworkBytes(expectedRead);
+        connection.awaitSelection(false);
+
+        connection._ticker.addTicker(new ServerIdleReadTimeoutTicker(mock(), 
connection._engine, 2000)
+        {
+            @Override
+            public int getTimeToNextTick(final long ignored)
+            {
+                return super.getTimeToNextTick(connection._currentTime.get());
+            }
+        });
+        connection.awaitSelection(false);
+        assertFalse(connection._readerIdle.get());
+        connection._currentTime.set(2000);
+        connection._connection.getSelectionTask().wakeup();
+        connection._closed.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+        assertTrue(connection._readerIdle.get(), "Waiting for record 
completion must not disable timeout processing");
+    }
+
     private void startScheduler(final int workers)
     {
         _scheduler = new NetworkConnectionScheduler(getTestName(), 1, workers, 
1L, task ->
@@ -212,13 +285,20 @@ class NonBlockingConnectionSchedulingTest extends 
UnitTestBase
     {
         final SSLSocket client = (SSLSocket) 
_sslContext.getSocketFactory().createSocket();
         client.setEnabledProtocols(new String[]{protocol});
-        final TestConnection connection = new TestConnection(_scheduler, 64 * 
1024, client, _sslContext);
+        final TestConnection connection = new TestConnection(_scheduler, 
NETWORK_BUFFER_SIZE, client, _sslContext);
         _connections.add(connection);
         client.startHandshake();
         assertEquals(protocol, client.getSession().getProtocol());
         return connection;
     }
 
+    private TestConnection createTlsEngineConnection() throws Exception
+    {
+        final TestConnection connection = new TestConnection(_scheduler, 
NETWORK_BUFFER_SIZE, new Socket(), _sslContext);
+        _connections.add(connection);
+        return connection;
+    }
+
     @AfterEach
     void tearDown() throws Exception
     {
@@ -286,6 +366,8 @@ class NonBlockingConnectionSchedulingTest extends 
UnitTestBase
                 new AtomicReference<>(Collections.emptyIterator());
         private final AtomicReference<SelectionInterest> _selectionInterest = 
new AtomicReference<>();
         private final BlockingQueue<Integer> _received = new 
LinkedBlockingQueue<>();
+        private final AtomicLong _networkBytesRead = new AtomicLong();
+        private final BlockingQueue<Long> _networkReads = new 
LinkedBlockingQueue<>();
         private final AggregateTicker _ticker = new AggregateTicker()
         {
             @Override
@@ -315,13 +397,13 @@ class NonBlockingConnectionSchedulingTest extends 
UnitTestBase
             try (final ServerSocketChannel listener = 
ServerSocketChannel.open())
             {
                 listener.bind(new 
InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
-                _client.setReceiveBufferSize(4096);
+                _client.setReceiveBufferSize(BUFFER_SIZE);
                 _client.setSoTimeout(TIMEOUT_MILLIS);
                 _client.connect(listener.getLocalAddress(), TIMEOUT_MILLIS);
                 _channel = listener.accept();
             }
             _channel.configureBlocking(false);
-            _channel.socket().setSendBufferSize(4096);
+            _channel.socket().setSendBufferSize(BUFFER_SIZE);
             when(_engine.getAggregateTicker()).thenReturn(_ticker);
             when(_engine.hasWork()).thenAnswer(invocation -> _hasWork.get());
             when(_engine.processPendingIterator()).thenAnswer(invocation -> 
_pending.get());
@@ -385,7 +467,19 @@ class NonBlockingConnectionSchedulingTest extends 
UnitTestBase
                     ? TransportEncryption.NONE
                     : TransportEncryption.TLS;
             final Set<TransportEncryption> encryptionSet = 
Set.of(transportEncryption);
-            _connection = new NonBlockingConnection(_channel, _engine, 
encryptionSet, () -> { }, scheduler, port);
+            _connection = new NonBlockingConnection(_channel, _engine, 
encryptionSet, () -> { }, scheduler, port)
+            {
+                @Override
+                protected long readFromNetwork() throws IOException
+                {
+                    final long count = super.readFromNetwork();
+                    if (count > 0)
+                    {
+                        _networkReads.add(_networkBytesRead.addAndGet(count));
+                    }
+                    return count;
+                }
+            };
             doAnswer(invocation ->
             {
                 _readerIdle.set(true);
@@ -409,6 +503,15 @@ class NonBlockingConnectionSchedulingTest extends 
UnitTestBase
             }
         }
 
+        private void awaitNetworkBytes(final long expected) throws 
InterruptedException
+        {
+            while (_networkBytesRead.get() < expected)
+            {
+                assertNotNull(_networkReads.poll(TIMEOUT_MILLIS, 
TimeUnit.MILLISECONDS),
+                        "The connection did not read the supplied TLS 
fragment");
+            }
+        }
+
         private void awaitWriteInterest() throws Exception
         {
             awaitSelection(true);
diff --git 
a/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSTest.java
 
b/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSTest.java
index 303bd7f7ae..7e9180cf2c 100644
--- 
a/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSTest.java
+++ 
b/broker-core/src/test/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSTest.java
@@ -147,8 +147,13 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
     }
 
     @ParameterizedTest
-    @ValueSource(strings = {"TLSv1.2", "TLSv1.3"})
-    void bufferedTlsInputRequestsContinuationAfterOutputDrains(final String 
protocol) throws Exception
+    @CsvSource({"TLSv1.2, false, 1", "TLSv1.2, false, 5", "TLSv1.2, false, -1",
+                "TLSv1.2, true, 1", "TLSv1.2, true, 5", "TLSv1.2, true, -1",
+                "TLSv1.3, false, 1", "TLSv1.3, false, 5", "TLSv1.3, false, -1",
+                "TLSv1.3, true, 1", "TLSv1.3, true, 5", "TLSv1.3, true, -1"})
+    void incompleteTlsInputWaitsForMoreNetworkData(final String protocol,
+                                                   final boolean blocked,
+                                                   final int prefixLength) 
throws Exception
     {
         try (final TlsConnection tls = new TlsConnection(protocol))
         {
@@ -156,14 +161,14 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
             final byte[] inbound = new byte[]{31, 32, 33};
             final byte[] outbound = new byte[]{41, 42, 43};
             tls.wrapPeer(ByteBuffer.wrap(inbound));
-            tls._readAllowance = 5;
-            tls._writeAllowance = 0;
+            tls._readAllowance = prefixLength < 0 ? tls._fromPeer.position() - 
1 : prefixLength;
+            tls._writeAllowance = blocked ? 0 : Integer.MAX_VALUE;
             tls.send(outbound);
             tls._connection.doWork();
 
             assertEquals(0, tls._received.size());
-            assertTrue(tls._connection.wantsWrite());
-            assertFalse(tls._connection.isStateChanged(), "Buffered TLS input 
must not spin behind a blocked write");
+            assertEquals(blocked, tls._connection.wantsWrite());
+            assertFalse(tls._connection.isStateChanged(), "An incomplete TLS 
record cannot make progress locally");
             tls._connection.doWork();
             assertFalse(tls._connection.isStateChanged());
             assertFalse(tls._connection.isPartialRead());
@@ -172,8 +177,7 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
             tls._connection.doWork();
             assertFalse(tls._connection.wantsWrite());
             assertFalse(tls._connection.isPartialRead(), "No new socket bytes 
were supplied during the drain");
-            assertTrue(tls._connection.isStateChanged(),
-                    "Retained TLS input must request a continuation after 
draining");
+            tls.assertWaitingForInput();
 
             tls._readAllowance = Integer.MAX_VALUE;
             tls._connection.doWork();
@@ -185,6 +189,110 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
         }
     }
 
+    @ParameterizedTest
+    @ValueSource(strings = {"TLSv1.2", "TLSv1.3"})
+    void completeRecordBeforeIncompleteRecordRequestsOnlyOneContinuation(final 
String protocol) throws Exception
+    {
+        try (final TlsConnection tls = new TlsConnection(protocol))
+        {
+            tls.finishHandshake();
+            final byte[] first = new byte[]{1, 2, 3};
+            final byte[] second = new byte[]{4, 5, 6};
+            for (int round = 0; round < 3; round++)
+            {
+                tls._received.reset();
+                tls.wrapPeer(ByteBuffer.wrap(first));
+                final int completeRecordLength = tls._fromPeer.position();
+                tls.wrapPeer(ByteBuffer.wrap(second));
+                tls._readAllowance = completeRecordLength + 5;
+
+                tls._connection.doWork();
+
+                assertArrayEquals(first, tls._received.toByteArray());
+                assertTrue(tls._connection.isStateChanged(), "New plaintext 
still requests a continuation");
+                tls.assertWaitingForInput();
+
+                tls._readAllowance = Integer.MAX_VALUE;
+                tls._connection.doWork();
+                assertArrayEquals(new byte[]{1, 2, 3, 4, 5, 6}, 
tls._received.toByteArray());
+                tls.assertWaitingForInput();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"TLSv1.2, 1", "TLSv1.2, 5", "TLSv1.2, 6",
+                "TLSv1.3, 1", "TLSv1.3, 5", "TLSv1.3, 6"})
+    void incompleteClientHelloWaitsForMoreNetworkData(final String protocol, 
final int prefixLength) throws Exception
+    {
+        try (final TlsConnection tls = new TlsConnection(protocol))
+        {
+            tls.wrapPeer(ByteBuffer.allocate(0));
+            tls._readAllowance = prefixLength;
+            tls._connection.doWork();
+            tls.assertWaitingForInput();
+
+            tls._readAllowance = Integer.MAX_VALUE;
+            tls.finishHandshake();
+            tls.wrapPeer(ByteBuffer.wrap(new byte[]{7, 8, 9}));
+            tls._connection.doWork();
+            assertArrayEquals(new byte[]{7, 8, 9}, 
tls._received.toByteArray());
+            tls.assertWaitingForInput();
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"TLSv1.2", "TLSv1.3"})
+    void incompleteRecordDoesNotBlockExplicitProtocolOutput(final String 
protocol) throws Exception
+    {
+        try (final TlsConnection tls = new TlsConnection(protocol))
+        {
+            tls.finishHandshake();
+            final byte[] inbound = new byte[]{1, 2, 3};
+            final byte[] outbound = new byte[]{4, 5, 6};
+            tls.wrapPeer(ByteBuffer.wrap(inbound));
+            tls._readAllowance = 5;
+            tls._connection.doWork();
+            tls.assertWaitingForInput();
+
+            
when(tls._engine.processPendingIterator()).thenReturn(List.<Runnable>of(() -> 
tls.send(outbound)).iterator());
+            tls._engine.notifyWork();
+            tls._connection.doWork();
+            tls.readAtPeer();
+            assertArrayEquals(outbound, tls._peerReceived.toByteArray());
+            tls.assertWaitingForInput();
+
+            tls._readAllowance = Integer.MAX_VALUE;
+            tls._connection.doWork();
+            assertArrayEquals(inbound, tls._received.toByteArray());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"TLSv1.2", "TLSv1.3"})
+    void recordRecoveryPreservesPostHandshakeWork(final String protocol) 
throws Exception
+    {
+        try (final TlsConnection tls = new TlsConnection(protocol))
+        {
+            tls.finishHandshake();
+            tls.wrapPeer(ByteBuffer.wrap(new byte[]{1, 2, 3}));
+            tls._readAllowance = 5;
+            tls._connection.doWork();
+            tls.assertWaitingForInput();
+            tls._readAllowance = Integer.MAX_VALUE;
+            tls._connection.doWork();
+            assertArrayEquals(new byte[]{1, 2, 3}, 
tls._received.toByteArray());
+
+            // Renegotiation in TLS 1.2, and key update in TLS 1.3.
+            tls._peer.beginHandshake();
+            tls.finishHandshake();
+            tls.wrapPeer(ByteBuffer.wrap(new byte[]{4, 5, 6}));
+            tls._connection.doWork();
+            assertArrayEquals(new byte[]{1, 2, 3, 4, 5, 6}, 
tls._received.toByteArray());
+            tls.assertWaitingForInput();
+        }
+    }
+
     /** Real TLS engines with explicitly granted socket capacity; all work 
runs on the test thread */
     private final class TlsConnection implements AutoCloseable
     {
@@ -194,6 +302,7 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
         private final ByteBuffer _toPeer = ByteBuffer.allocate(4 * 
NETWORK_BUFFER_SIZE);
         private final ByteArrayOutputStream _received = new 
ByteArrayOutputStream();
         private final ByteArrayOutputStream _peerReceived = new 
ByteArrayOutputStream();
+        private final ProtocolEngine _engine = mock(ProtocolEngine.class);
         private final NonBlockingConnection _connection;
         private int _writeAllowance = Integer.MAX_VALUE;
         private int _readAllowance = Integer.MAX_VALUE;
@@ -229,7 +338,7 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
                 }
                 return written;
             });
-            final ProtocolEngine engine = mock(ProtocolEngine.class);
+            final ProtocolEngine engine = _engine;
             when(engine.getAggregateTicker()).thenReturn(new 
AggregateTicker());
             when(engine.processPendingIterator()).thenAnswer(invocation -> 
Collections.emptyIterator());
             when(engine.hasWork()).thenAnswer(invocation -> _hasWork);
@@ -348,6 +457,20 @@ class NonBlockingConnectionTLSTest extends UnitTestBase
             }
         }
 
+        private void assertWaitingForInput()
+        {
+            final int withheld = _fromPeer.position();
+            for (int pass = 0; pass < 16; pass++)
+            {
+                assertFalse(_connection.doWork(), "Waiting for input must keep 
the connection open");
+                assertFalse(_connection.isStateChanged(), "A zero-read pass 
must not request another worker turn");
+                assertFalse(_connection.isPartialRead(), "The socket supplied 
no new bytes");
+                assertTrue(_connection.wantsRead(), "The selector must 
continue watching for input");
+                assertFalse(_connection.wantsWrite());
+                assertEquals(withheld, _fromPeer.position(), "The remainder 
must remain withheld");
+            }
+        }
+
         @Override
         public void close()
         {
diff --git 
a/broker-core/src/test/java/org/apache/qpid/server/transport/TlsTestPeer.java 
b/broker-core/src/test/java/org/apache/qpid/server/transport/TlsTestPeer.java
new file mode 100644
index 0000000000..39a8fec567
--- /dev/null
+++ 
b/broker-core/src/test/java/org/apache/qpid/server/transport/TlsTestPeer.java
@@ -0,0 +1,113 @@
+/*
+ * 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.qpid.server.transport;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.net.Socket;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+
+/** A real TLS peer whose encrypted records can be split between socket 
writes. */
+final class TlsTestPeer
+{
+    private static final int CAPACITY = 64 * 1024;
+    private final SSLEngine _engine;
+    private final Socket _socket;
+
+    TlsTestPeer(final SSLContext context, final String protocol, final Socket 
socket) throws Exception
+    {
+        _socket = socket;
+        _engine = context.createSSLEngine("localhost", socket.getPort());
+        _engine.setUseClientMode(true);
+        _engine.setEnabledProtocols(new String[]{protocol});
+        _engine.beginHandshake();
+        handshake();
+    }
+
+    byte[] wrap(final byte[] plaintext) throws Exception
+    {
+        final ByteBuffer input = ByteBuffer.wrap(plaintext);
+        final ByteBuffer output = ByteBuffer.allocate(CAPACITY);
+        final SSLEngineResult result = _engine.wrap(input, output);
+        assertEquals(SSLEngineResult.Status.OK, result.getStatus());
+        assertEquals(plaintext.length, result.bytesConsumed());
+        assertTrue(result.bytesProduced() > 0);
+        return Arrays.copyOf(output.array(), output.position());
+    }
+
+    void send(final byte[] bytes) throws Exception
+    {
+        _socket.getOutputStream().write(bytes);
+    }
+
+    private void handshake() throws Exception
+    {
+        final ByteBuffer input = ByteBuffer.allocate(CAPACITY);
+        final ByteBuffer output = ByteBuffer.allocate(CAPACITY);
+        final ByteBuffer application = ByteBuffer.allocate(CAPACITY);
+        for (int step = 0; step < 1000; step++)
+        {
+            switch (_engine.getHandshakeStatus())
+            {
+                case NOT_HANDSHAKING:
+                    return;
+                case NEED_TASK:
+                    Runnable task;
+                    while ((task = _engine.getDelegatedTask()) != null)
+                    {
+                        task.run();
+                    }
+                    break;
+                case NEED_WRAP:
+                    output.clear();
+                    assertEquals(SSLEngineResult.Status.OK,
+                                 _engine.wrap(ByteBuffer.allocate(0), 
output).getStatus());
+                    _socket.getOutputStream().write(output.array(), 0, 
output.position());
+                    break;
+                case NEED_UNWRAP:
+                case NEED_UNWRAP_AGAIN:
+                    input.flip();
+                    final SSLEngineResult result = _engine.unwrap(input, 
application);
+                    input.compact();
+                    if (result.getStatus() == 
SSLEngineResult.Status.BUFFER_UNDERFLOW)
+                    {
+                        assertTrue(input.hasRemaining());
+                        final int count = 
_socket.getInputStream().read(input.array(), input.position(), 
input.remaining());
+                        assertTrue(count > 0, "Peer closed during the 
handshake");
+                        input.position(input.position() + count);
+                    }
+                    else
+                    {
+                        assertEquals(SSLEngineResult.Status.OK, 
result.getStatus());
+                    }
+                    break;
+                default:
+                    fail("Unexpected handshake status: " + 
_engine.getHandshakeStatus());
+            }
+        }
+        fail("TLS handshake did not finish");
+    }
+}


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

Reply via email to