1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.handler.ssl;
17
18 import io.netty5.buffer.api.BufferAllocator;
19
20 import javax.net.ssl.X509KeyManager;
21 import java.util.Iterator;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24
25
26
27
28
29 final class OpenSslCachingKeyMaterialProvider extends OpenSslKeyMaterialProvider {
30
31 private final int maxCachedEntries;
32 private volatile boolean full;
33 private final ConcurrentMap<String, OpenSslKeyMaterial> cache = new ConcurrentHashMap<>();
34
35 OpenSslCachingKeyMaterialProvider(X509KeyManager keyManager, String password, int maxCachedEntries) {
36 super(keyManager, password);
37 this.maxCachedEntries = maxCachedEntries;
38 }
39
40 @Override
41 OpenSslKeyMaterial chooseKeyMaterial(BufferAllocator allocator, String alias) throws Exception {
42 OpenSslKeyMaterial material = cache.get(alias);
43 if (material == null) {
44 material = super.chooseKeyMaterial(allocator, alias);
45 if (material == null) {
46
47 return null;
48 }
49
50 if (full) {
51 return material;
52 }
53 if (cache.size() > maxCachedEntries) {
54 full = true;
55
56 return material;
57 }
58 OpenSslKeyMaterial old = cache.putIfAbsent(alias, material);
59 if (old != null) {
60 material.release();
61 material = old;
62 }
63 }
64
65 return material.retain();
66 }
67
68 @Override
69 void destroy() {
70
71 do {
72 Iterator<OpenSslKeyMaterial> iterator = cache.values().iterator();
73 while (iterator.hasNext()) {
74 iterator.next().release();
75 iterator.remove();
76 }
77 } while (!cache.isEmpty());
78 }
79 }