GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Auto-port 5.0: Weakly reference engines from the OpenSSL engine map (… · netty/netty@e954354

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • handler/src
    • main/java/io/netty/handler/ssl
      • OpenSslClientSessionCache.java
      • OpenSslEngineMap.java
      • OpenSslSessionCache.java
      • ReferenceCountedOpenSslClientContext.java
      • ReferenceCountedOpenSslContext.java
      • ReferenceCountedOpenSslEngine.java
      • ReferenceCountedOpenSslServerContext.java
    • test/java/io/netty/handler/ssl
      • OpenSslEngineTest.java
      • ReferenceCountedOpenSslEngineTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎handler/src/main/java/io/netty/handler/ssl/OpenSslClientSessionCache.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/OpenSslClientSessionCache.java
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
final class OpenSslClientSessionCache extends OpenSslSessionCache {
3232
private final Map<HostPort, Set<NativeSslSession>> sessions = new HashMap<>();
3333

34-
OpenSslClientSessionCache(Map<Long, ReferenceCountedOpenSslEngine> engines) {
34+
OpenSslClientSessionCache(OpenSslEngineMap engines) {
3535
super(engines);
3636
}
3737

Collapse file

‎handler/src/main/java/io/netty/handler/ssl/OpenSslEngineMap.java‎

Copy file name to clipboard
+61Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* Copyright 2026 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.handler.ssl;
17+
18+
import java.lang.ref.WeakReference;
19+
import java.util.Map;
20+
import java.util.concurrent.ConcurrentHashMap;
21+
22+
/**
23+
* Maps a native {@code SSL*} pointer to its {@link ReferenceCountedOpenSslEngine} so native OpenSSL callbacks
24+
* (certificate verification, private-key operations, certificate (de)compression) can recover the engine from the
25+
* raw pointer they are handed.
26+
* <p>
27+
* Engines are held weakly so a leaked engine is not pinned by the long-lived parent
28+
* {@link ReferenceCountedOpenSslContext} (a live engine is always strongly reachable via its {@link SslHandler}, and
29+
* on the stack during a callback, so weak retention never collects a usable one). For {@link SslProvider#OPENSSL}
30+
* this lets {@link OpenSslEngine#finalize()} reclaim the native {@code SSL*} without waiting for the whole context to
31+
* be collected; a leaked {@link SslProvider#OPENSSL_REFCNT} engine has no finalizer so its native memory still leaks,
32+
* but it becomes collectable and so is reported by the {@code ResourceLeakDetector} rather than pinned silently.
33+
* <p>
34+
* Entries are removed in {@link ReferenceCountedOpenSslEngine#shutdown()}, so the map does not grow in steady state.
35+
* A cleared {@link WeakReference} lingers only for a leaked {@code OPENSSL_REFCNT} engine (whose {@code SSL*} is never
36+
* freed, hence never reused); such a husk is tiny, dwarfed by the native memory it marks, and is deliberately left as
37+
* a heap-inspectable leak signal. Do not reap it (e.g. via a {@code ReferenceQueue}): {@link #get(long)} already
38+
* yields {@code null} for a cleared reference, so reaping would only erase that signal.
39+
*/
40+
final class OpenSslEngineMap {
41+
42+
private final Map<Long, WeakReference<ReferenceCountedOpenSslEngine>> engines =
43+
new ConcurrentHashMap<Long, WeakReference<ReferenceCountedOpenSslEngine>>();
44+
45+
void add(long ssl, ReferenceCountedOpenSslEngine engine) {
46+
// A fresh SSL_new() pointer maps to nothing yet: an SSL* is reused only after shutdown() removed its entry
47+
// (remove-before-freeSSL), and a husk survives only for a never-freed, never-reused SSL*.
48+
WeakReference<ReferenceCountedOpenSslEngine> prev =
49+
engines.put(ssl, new WeakReference<ReferenceCountedOpenSslEngine>(engine));
50+
assert prev == null : "OpenSslEngineMap already had an entry for SSL* 0x" + Long.toHexString(ssl);
51+
}
52+
53+
void remove(long ssl) {
54+
engines.remove(ssl);
55+
}
56+
57+
ReferenceCountedOpenSslEngine get(long ssl) {
58+
WeakReference<ReferenceCountedOpenSslEngine> ref = engines.get(ssl);
59+
return ref == null ? null : ref.get();
60+
}
61+
}
Collapse file

‎handler/src/main/java/io/netty/handler/ssl/OpenSslSessionCache.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/OpenSslSessionCache.java
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class OpenSslSessionCache implements SSLSessionCache {
4949
DEFAULT_CACHE_SIZE = 20480;
5050
}
5151
}
52-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
52+
private final OpenSslEngineMap engines;
5353

5454
private final Map<OpenSslSessionId, NativeSslSession> sessions =
5555
new LinkedHashMap<OpenSslSessionId, NativeSslSession>() {
@@ -74,7 +74,7 @@ protected boolean removeEldestEntry(Map.Entry<OpenSslSessionId, NativeSslSession
7474
private final AtomicInteger sessionTimeout = new AtomicInteger(300);
7575
private int sessionCounter;
7676

77-
OpenSslSessionCache(Map<Long, ReferenceCountedOpenSslEngine> engines) {
77+
OpenSslSessionCache(OpenSslEngineMap engines) {
7878
this.engines = engines;
7979
}
8080

Collapse file

‎handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslClientContext.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslClientContext.java
+6-6Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ public OpenSslSessionContext sessionContext() {
103103
}
104104

105105
static OpenSslSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
106-
Map<Long, ReferenceCountedOpenSslEngine> engines,
106+
OpenSslEngineMap engines,
107107
X509Certificate[] trustCertCollection,
108108
TrustManagerFactory trustManagerFactory,
109109
X509Certificate[] keyCertChain, PrivateKey key,
@@ -213,7 +213,7 @@ static OpenSslSessionContext newSessionContext(ReferenceCountedOpenSslContext th
213213
}
214214

215215
private static void setVerifyCallback(long ctx,
216-
Map<Long, ReferenceCountedOpenSslEngine> engines,
216+
OpenSslEngineMap engines,
217217
X509TrustManager manager) {
218218
// Use this to prevent an error when running on java < 7
219219
if (useExtendedTrustManager(manager)) {
@@ -233,7 +233,7 @@ static final class OpenSslClientSessionContext extends OpenSslSessionContext {
233233
private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
234234
private final X509TrustManager manager;
235235

236-
TrustManagerVerifyCallback(Map<Long, ReferenceCountedOpenSslEngine> engines, X509TrustManager manager) {
236+
TrustManagerVerifyCallback(OpenSslEngineMap engines, X509TrustManager manager) {
237237
super(engines);
238238
this.manager = manager;
239239
}
@@ -248,7 +248,7 @@ void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, S
248248
private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
249249
private final X509ExtendedTrustManager manager;
250250

251-
ExtendedTrustManagerVerifyCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
251+
ExtendedTrustManagerVerifyCallback(OpenSslEngineMap engines,
252252
X509ExtendedTrustManager manager) {
253253
super(engines);
254254
this.manager = manager;
@@ -262,10 +262,10 @@ void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, S
262262
}
263263

264264
private static final class OpenSslClientCertificateCallback implements CertificateCallback {
265-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
265+
private final OpenSslEngineMap engines;
266266
private final OpenSslKeyMaterialManager keyManagerHolder;
267267

268-
OpenSslClientCertificateCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
268+
OpenSslClientCertificateCallback(OpenSslEngineMap engines,
269269
OpenSslKeyMaterialManager keyManagerHolder) {
270270
this.engines = engines;
271271
this.keyManagerHolder = keyManagerHolder;
Collapse file

‎handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslContext.java
+10-12Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,6 @@
5757
import java.util.List;
5858
import java.util.Map;
5959
import java.util.Set;
60-
import java.util.concurrent.ConcurrentHashMap;
61-
import java.util.concurrent.ConcurrentMap;
6260
import java.util.concurrent.Executor;
6361
import java.util.concurrent.locks.Lock;
6462
import java.util.concurrent.locks.ReadWriteLock;
@@ -170,7 +168,7 @@ protected void deallocate() {
170168
final boolean hasTmpDhKeys;
171169
final String[] groups;
172170
final boolean enableOcsp;
173-
final ConcurrentMap<Long, ReferenceCountedOpenSslEngine> engines = new ConcurrentHashMap<>();
171+
final OpenSslEngineMap engines = new OpenSslEngineMap();
174172
final ReadWriteLock ctxLock = new ReentrantReadWriteLock();
175173
final List<OpenSslCredential> credentials = new ArrayList<>();
176174

@@ -880,9 +878,9 @@ public final boolean release(int decrement) {
880878
}
881879

882880
abstract static class AbstractCertificateVerifier extends CertificateVerifier {
883-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
881+
private final OpenSslEngineMap engines;
884882

885-
AbstractCertificateVerifier(Map<Long, ReferenceCountedOpenSslEngine> engines) {
883+
AbstractCertificateVerifier(OpenSslEngineMap engines) {
886884
this.engines = engines;
887885
}
888886

@@ -1147,7 +1145,7 @@ static OpenSslKeyMaterialProvider setupSecurityProviderSignatureSource(
11471145
}
11481146
}
11491147

1150-
private static ReferenceCountedOpenSslEngine retrieveEngine(Map<Long, ReferenceCountedOpenSslEngine> engines,
1148+
private static ReferenceCountedOpenSslEngine retrieveEngine(OpenSslEngineMap engines,
11511149
long ssl)
11521150
throws SSLException {
11531151
ReferenceCountedOpenSslEngine engine = engines.get(ssl);
@@ -1160,9 +1158,9 @@ private static ReferenceCountedOpenSslEngine retrieveEngine(Map<Long, ReferenceC
11601158

11611159
private static final class PrivateKeyMethod implements SSLPrivateKeyMethod {
11621160

1163-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
1161+
private final OpenSslEngineMap engines;
11641162
private final OpenSslPrivateKeyMethod keyMethod;
1165-
PrivateKeyMethod(Map<Long, ReferenceCountedOpenSslEngine> engines, OpenSslPrivateKeyMethod keyMethod) {
1163+
PrivateKeyMethod(OpenSslEngineMap engines, OpenSslPrivateKeyMethod keyMethod) {
11661164
this.engines = engines;
11671165
this.keyMethod = keyMethod;
11681166
}
@@ -1192,10 +1190,10 @@ public byte[] decrypt(long ssl, byte[] input) throws Exception {
11921190

11931191
private static final class AsyncPrivateKeyMethod implements AsyncSSLPrivateKeyMethod {
11941192

1195-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
1193+
private final OpenSslEngineMap engines;
11961194
private final OpenSslAsyncPrivateKeyMethod keyMethod;
11971195

1198-
AsyncPrivateKeyMethod(Map<Long, ReferenceCountedOpenSslEngine> engines,
1196+
AsyncPrivateKeyMethod(OpenSslEngineMap engines,
11991197
OpenSslAsyncPrivateKeyMethod keyMethod) {
12001198
this.engines = engines;
12011199
this.keyMethod = keyMethod;
@@ -1261,10 +1259,10 @@ private static byte[] verifyResult(byte[] result) throws SignatureException {
12611259
}
12621260

12631261
private static final class CompressionAlgorithm implements CertificateCompressionAlgo {
1264-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
1262+
private final OpenSslEngineMap engines;
12651263
private final OpenSslCertificateCompressionAlgorithm compressionAlgorithm;
12661264

1267-
CompressionAlgorithm(Map<Long, ReferenceCountedOpenSslEngine> engines,
1265+
CompressionAlgorithm(OpenSslEngineMap engines,
12681266
OpenSslCertificateCompressionAlgorithm compressionAlgorithm) {
12691267
this.engines = engines;
12701268
this.compressionAlgorithm = compressionAlgorithm;
Collapse file

‎handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ protected void deallocate() {
205205
final boolean jdkCompatibilityMode;
206206
private final boolean clientMode;
207207
final ByteBufAllocator alloc;
208-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
208+
private final OpenSslEngineMap engines;
209209
private final OpenSslApplicationProtocolNegotiator apn;
210210
private final ReferenceCountedOpenSslContext parentContext;
211211
private final OpenSslInternalSession session;
@@ -422,8 +422,8 @@ public List<byte[]> getStatusResponses() {
422422
// object so we need to retain a reference to the parent context.
423423
parentContext = context;
424424

425-
// Adding the OpenSslEngine to the OpenSslEngineMap so it can be used in the AbstractCertificateVerifier.
426-
engines.put(ssl, this);
425+
// Register for the SSL* -> engine reverse lookup used by native callbacks; held weakly (see OpenSslEngineMap).
426+
engines.add(ssl, this);
427427

428428
// Only create the leak after everything else was executed and so ensure we don't produce a false-positive for
429429
// the ResourceLeakDetector.
Collapse file

‎handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslServerContext.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslServerContext.java
+8-8Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public OpenSslServerSessionContext sessionContext() {
9898
}
9999

100100
static OpenSslServerSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
101-
Map<Long, ReferenceCountedOpenSslEngine> engines,
101+
OpenSslEngineMap engines,
102102
X509Certificate[] trustCertCollection,
103103
TrustManagerFactory trustManagerFactory,
104104
X509Certificate[] keyCertChain, PrivateKey key,
@@ -217,7 +217,7 @@ static OpenSslServerSessionContext newSessionContext(ReferenceCountedOpenSslCont
217217
}
218218

219219
private static void setVerifyCallback(long ctx,
220-
Map<Long, ReferenceCountedOpenSslEngine> engines,
220+
OpenSslEngineMap engines,
221221
X509TrustManager manager) {
222222
// Use this to prevent an error when running on java < 7
223223
if (useExtendedTrustManager(manager)) {
@@ -229,10 +229,10 @@ private static void setVerifyCallback(long ctx,
229229
}
230230

231231
private static final class OpenSslServerCertificateCallback implements CertificateCallback {
232-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
232+
private final OpenSslEngineMap engines;
233233
private final OpenSslKeyMaterialManager keyManagerHolder;
234234

235-
OpenSslServerCertificateCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
235+
OpenSslServerCertificateCallback(OpenSslEngineMap engines,
236236
OpenSslKeyMaterialManager keyManagerHolder) {
237237
this.engines = engines;
238238
this.keyManagerHolder = keyManagerHolder;
@@ -263,7 +263,7 @@ public void handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincip
263263
private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
264264
private final X509TrustManager manager;
265265

266-
TrustManagerVerifyCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
266+
TrustManagerVerifyCallback(OpenSslEngineMap engines,
267267
X509TrustManager manager) {
268268
super(engines);
269269
this.manager = manager;
@@ -279,7 +279,7 @@ void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, S
279279
private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
280280
private final X509ExtendedTrustManager manager;
281281

282-
ExtendedTrustManagerVerifyCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
282+
ExtendedTrustManagerVerifyCallback(OpenSslEngineMap engines,
283283
X509ExtendedTrustManager manager) {
284284
super(engines);
285285
this.manager = manager;
@@ -293,9 +293,9 @@ void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, S
293293
}
294294

295295
private static final class OpenSslSniHostnameMatcher implements SniHostNameMatcher {
296-
private final Map<Long, ReferenceCountedOpenSslEngine> engines;
296+
private final OpenSslEngineMap engines;
297297

298-
OpenSslSniHostnameMatcher(Map<Long, ReferenceCountedOpenSslEngine> engines) {
298+
OpenSslSniHostnameMatcher(OpenSslEngineMap engines) {
299299
this.engines = engines;
300300
}
301301

Collapse file

‎handler/src/test/java/io/netty/handler/ssl/OpenSslEngineTest.java‎

Copy file name to clipboardExpand all lines: handler/src/test/java/io/netty/handler/ssl/OpenSslEngineTest.java
+35Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import org.junit.jupiter.api.AfterEach;
3434
import org.junit.jupiter.api.BeforeAll;
3535
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.api.Timeout;
3637
import org.junit.jupiter.api.condition.EnabledIf;
3738
import org.junit.jupiter.api.extension.ExtendWith;
3839
import org.junit.jupiter.api.function.Executable;
@@ -55,6 +56,7 @@
5556
import java.util.List;
5657
import java.util.Set;
5758
import java.util.concurrent.ThreadLocalRandom;
59+
import java.util.concurrent.TimeUnit;
5860
import javax.crypto.Cipher;
5961
import javax.crypto.spec.IvParameterSpec;
6062
import javax.crypto.spec.SecretKeySpec;
@@ -1515,6 +1517,39 @@ public void execute() throws Throwable {
15151517
}
15161518
}
15171519

1520+
// Pins OPENSSL (not sslClientProvider()) because only the OPENSSL engine has a finalizer to drive the reclaim
1521+
// asserted here; the OPENSSL_REFCNT subclass overrides this to a no-op (it has no finalizer). Verifies that a
1522+
// leaked engine is collected and releases its parent context while the context is still alive -- only possible
1523+
// because OpenSslEngineMap holds engines weakly rather than pinning them for the context's lifetime.
1524+
@Test
1525+
@Timeout(value = 30, unit = TimeUnit.SECONDS)
1526+
public void leakedEngineIsReclaimedWhileContextAlive() throws Exception {
1527+
assumeTrue(OpenSsl.isAvailable());
1528+
1529+
SslContext ctx = SslContextBuilder.forClient()
1530+
.trustManager(InsecureTrustManagerFactory.INSTANCE)
1531+
.sslProvider(OPENSSL)
1532+
.build();
1533+
try {
1534+
// newEngine retains the context, so its refCnt goes from 1 to 2.
1535+
SSLEngine engine = ctx.newEngine(UnpooledByteBufAllocator.DEFAULT);
1536+
assertEquals(2, ReferenceCountUtil.refCnt(ctx));
1537+
1538+
// Drop the engine without releasing it, simulating a leak (e.g. handlerRemoved0 never firing).
1539+
engine = null;
1540+
1541+
// Collection triggers OpenSslEngine.finalize(), which releases the context (2 -> 1).
1542+
while (ReferenceCountUtil.refCnt(ctx) != 1) {
1543+
System.gc();
1544+
System.runFinalization();
1545+
Thread.sleep(50);
1546+
}
1547+
assertEquals(1, ReferenceCountUtil.refCnt(ctx));
1548+
} finally {
1549+
ReferenceCountUtil.release(ctx);
1550+
}
1551+
}
1552+
15181553
@Override
15191554
protected SslProvider sslClientProvider() {
15201555
return OPENSSL;
Collapse file

‎handler/src/test/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngineTest.java‎

Copy file name to clipboardExpand all lines: handler/src/test/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngineTest.java
+7Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ protected SslProvider sslServerProvider() {
3939
return SslProvider.OPENSSL_REFCNT;
4040
}
4141

42+
// OPENSSL_REFCNT has no finalizer, so the superclass's OPENSSL-only reclaim test does not apply here.
43+
// Overriding it without @Test disables it for this subclass.
44+
@Override
45+
public void leakedEngineIsReclaimedWhileContextAlive() {
46+
// noop
47+
}
48+
4249
@MethodSource("newTestParams")
4350
@ParameterizedTest
4451
public void testNotLeakOnException(SSLEngineTestParam param) throws Exception {

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.