Skip to content

Commit a806a91

Browse files
committed
SSLSocketChannel2: close stale connection with no handshake in 60s
Signed-off-by: Juhyung Park <qkrwngud825@gmail.com>
1 parent b4fb6b3 commit a806a91

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

src/main/java/org/java_websocket/SSLSocketChannel2.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@
3939
import java.util.List;
4040
import java.util.concurrent.ExecutionException;
4141
import java.util.concurrent.ExecutorService;
42+
import java.util.concurrent.Executors;
4243
import java.util.concurrent.Future;
44+
import java.util.concurrent.ScheduledExecutorService;
45+
import java.util.concurrent.ScheduledFuture;
46+
import java.util.concurrent.TimeUnit;
4347
import javax.net.ssl.SSLEngine;
4448
import javax.net.ssl.SSLEngineResult;
4549
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
@@ -105,6 +109,12 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel, ISSLC
105109
**/
106110
protected int bufferallocations = 0;
107111

112+
/**
113+
* Scheduler to close the socket when the handshake takes too long
114+
*/
115+
protected ScheduledExecutorService closeSocketScheduler;
116+
protected ScheduledFuture<?> closeSocketTask;
117+
108118
public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorService exec,
109119
SelectionKey key) throws IOException {
110120
if (channel == null || sslEngine == null || exec == null) {
@@ -127,6 +137,16 @@ public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorSer
127137
// kick off handshake
128138
socketChannel.write(wrap(emptybuffer));// initializes res
129139
processHandshake(false);
140+
141+
// Close stale connection with no handshake in 60s
142+
this.closeSocketScheduler = Executors.newSingleThreadScheduledExecutor();
143+
this.closeSocketTask = closeSocketScheduler.schedule(() -> {
144+
try {
145+
close();
146+
} catch (IOException e) {
147+
// Ignored
148+
}
149+
}, 60, TimeUnit.SECONDS);
130150
}
131151

132152
private void consumeFutureUninterruptible(Future<?> f) {
@@ -188,6 +208,11 @@ private synchronized void processHandshake(boolean isReading) throws IOException
188208
|| sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
189209
socketChannel.write(wrap(emptybuffer));
190210
if (writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED) {
211+
if (closeSocketTask != null) {
212+
closeSocketTask.cancel(false);
213+
closeSocketTask = null;
214+
closeSocketScheduler = null;
215+
}
191216
createBuffers(sslEngine.getSession());
192217
return;
193218
} else {

0 commit comments

Comments
 (0)