diff --git a/handler/src/main/java/io/netty/handler/ssl/SniHandler.java b/handler/src/main/java/io/netty/handler/ssl/SniHandler.java index 7fc70d1258..77d558f2a4 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SniHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SniHandler.java @@ -26,6 +26,7 @@ import io.netty.util.AsyncMapping; import io.netty.util.CharsetUtil; import io.netty.util.DomainNameMapping; import io.netty.util.Mapping; +import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.Promise; @@ -38,6 +39,8 @@ import java.net.SocketAddress; import java.util.List; import java.util.Locale; +import javax.net.ssl.SSLEngine; + /** *
Enables SNI * (Server Name Indication) extension for server side SSL. For clients @@ -303,9 +306,19 @@ public class SniHandler extends ByteToMessageDecoder implements ChannelOutboundH } private void replaceHandler(ChannelHandlerContext ctx, Selection selection) { + SSLEngine sslEngine = null; this.selection = selection; - SslHandler sslHandler = selection.context.newHandler(ctx.alloc()); - ctx.pipeline().replace(this, SslHandler.class.getName(), sslHandler); + try { + sslEngine = selection.context.newEngine(ctx.alloc()); + ctx.pipeline().replace(this, SslHandler.class.getName(), selection.context.newHandler(sslEngine)); + } catch (Throwable cause) { + this.selection = EMPTY_SELECTION; + // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not + // transferred to the SslHandler. + // See https://github.com/netty/netty/issues/5678 + ReferenceCountUtil.safeRelease(sslEngine); + ctx.fireExceptionCaught(cause); + } } @Override diff --git a/handler/src/main/java/io/netty/handler/ssl/SslContext.java b/handler/src/main/java/io/netty/handler/ssl/SslContext.java index 9e3986da9a..7ae00dba62 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslContext.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslContext.java @@ -869,7 +869,7 @@ public abstract class SslContext { return newHandler(newEngine(alloc, peerHost, peerPort)); } - private static SslHandler newHandler(SSLEngine engine) { + static SslHandler newHandler(SSLEngine engine) { return new SslHandler(engine); }