3939import java .util .List ;
4040import java .util .concurrent .ExecutionException ;
4141import java .util .concurrent .ExecutorService ;
42+ import java .util .concurrent .Executors ;
4243import java .util .concurrent .Future ;
44+ import java .util .concurrent .ScheduledExecutorService ;
45+ import java .util .concurrent .ScheduledFuture ;
46+ import java .util .concurrent .TimeUnit ;
4347import javax .net .ssl .SSLEngine ;
4448import javax .net .ssl .SSLEngineResult ;
4549import 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