Skip to content

Commit

Permalink
Update SSLSocketChannel2.java
Browse files Browse the repository at this point in the history
  • Loading branch information
bergice committed Dec 20, 2022
1 parent aad6654 commit 312d57c
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions src/main/java/org/java_websocket/SSLSocketChannel2.java
Expand Up @@ -105,6 +105,12 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel, ISSLC
**/
protected int bufferallocations = 0;

/**
* 2022-06-17 Handshake start time in WSS for the underlying channel.
* If wss handshake is not completed in 10s, close this channel to prevent cpu overload or unexpected channel error. see #896.
*/
protected long handshakeStartTime = System.currentTimeMillis() ;

public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorService exec,
SelectionKey key) throws IOException {
if (channel == null || sslEngine == null || exec == null) {
Expand Down Expand Up @@ -385,19 +391,29 @@ public boolean isConnected() {
public void close() throws IOException {
sslEngine.closeOutbound();
sslEngine.getSession().invalidate();
try {
if (socketChannel.isOpen()) {
socketChannel.write(wrap(emptybuffer));
}
} finally { // in case socketChannel.write produce exception - channel will never close
socketChannel.close();
if (socketChannel.isOpen()) {
socketChannel.write(wrap(emptybuffer));// FIXME what if not all bytes can be written
}
socketChannel.close();
}

private boolean isHandShakeComplete() {
HandshakeStatus status = sslEngine.getHandshakeStatus();
return status == SSLEngineResult.HandshakeStatus.FINISHED
|| status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;

// handshake status
boolean ret = status == SSLEngineResult.HandshakeStatus.FINISHED
|| status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;

if ( ret == false )
{
// 2022-06-17 If wss handshake is not completed in 10s, close this channel to prevent cpu overload or unexpected channel error. see #896.
if ( handshakeStartTime > 0 && ( System.currentTimeMillis() - handshakeStartTime ) > 10000 )
{
try{close() ;}catch(Exception ex){} ;
}
}

return ret;
}

public SelectableChannel configureBlocking(boolean b) throws IOException {
Expand Down Expand Up @@ -498,4 +514,4 @@ private void tryRestoreCryptedData() {
saveCryptData = null;
}
}
}
}

0 comments on commit 312d57c

Please sign in to comment.