Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.naming/share/classes/com/sun/jndi/ldap/LdapPoolManager.java
41161 views
1
/*
2
* Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package com.sun.jndi.ldap;
27
28
import java.io.PrintStream;
29
import java.io.OutputStream;
30
import java.util.Hashtable;
31
import java.util.Locale;
32
import java.util.StringTokenizer;
33
34
import javax.naming.ldap.Control;
35
import javax.naming.NamingException;
36
import javax.naming.CommunicationException;
37
import java.security.AccessController;
38
import java.security.PrivilegedAction;
39
40
import com.sun.jndi.ldap.pool.PoolCleaner;
41
import com.sun.jndi.ldap.pool.Pool;
42
import jdk.internal.misc.InnocuousThread;
43
44
/**
45
* Contains utilities for managing connection pools of LdapClient.
46
* Contains method for
47
* - checking whether attempted connection creation may be pooled
48
* - creating a pooled connection
49
* - closing idle connections.
50
*
51
* If a timeout period has been configured, then it will automatically
52
* close and remove idle connections (those that have not been
53
* used for the duration of the timeout period).
54
*
55
* @author Rosanna Lee
56
*/
57
58
@SuppressWarnings("removal")
59
public final class LdapPoolManager {
60
private static final String DEBUG =
61
"com.sun.jndi.ldap.connect.pool.debug";
62
63
public static final boolean debug =
64
"all".equalsIgnoreCase(getProperty(DEBUG, null));
65
66
public static final boolean trace = debug ||
67
"fine".equalsIgnoreCase(getProperty(DEBUG, null));
68
69
// ---------- System properties for connection pooling
70
71
// Authentication mechanisms of connections that may be pooled
72
private static final String POOL_AUTH =
73
"com.sun.jndi.ldap.connect.pool.authentication";
74
75
// Protocol types of connections that may be pooled
76
private static final String POOL_PROTOCOL =
77
"com.sun.jndi.ldap.connect.pool.protocol";
78
79
// Maximum number of identical connections per pool
80
private static final String MAX_POOL_SIZE =
81
"com.sun.jndi.ldap.connect.pool.maxsize";
82
83
// Preferred number of identical connections per pool
84
private static final String PREF_POOL_SIZE =
85
"com.sun.jndi.ldap.connect.pool.prefsize";
86
87
// Initial number of identical connections per pool
88
private static final String INIT_POOL_SIZE =
89
"com.sun.jndi.ldap.connect.pool.initsize";
90
91
// Milliseconds to wait before closing idle connections
92
private static final String POOL_TIMEOUT =
93
"com.sun.jndi.ldap.connect.pool.timeout";
94
95
// Properties for DIGEST
96
private static final String SASL_CALLBACK =
97
"java.naming.security.sasl.callback";
98
99
// --------- Constants
100
private static final int DEFAULT_MAX_POOL_SIZE = 0;
101
private static final int DEFAULT_PREF_POOL_SIZE = 0;
102
private static final int DEFAULT_INIT_POOL_SIZE = 1;
103
private static final int DEFAULT_TIMEOUT = 0; // no timeout
104
private static final String DEFAULT_AUTH_MECHS = "none simple";
105
private static final String DEFAULT_PROTOCOLS = "plain";
106
107
private static final int NONE = 0; // indices into pools
108
private static final int SIMPLE = 1;
109
private static final int DIGEST = 2;
110
111
// --------- static fields
112
private static final long idleTimeout;// ms to wait before closing idle conn
113
private static final int maxSize; // max num of identical conns/pool
114
private static final int prefSize; // preferred num of identical conns/pool
115
private static final int initSize; // initial num of identical conns/pool
116
117
private static boolean supportPlainProtocol = false;
118
private static boolean supportSslProtocol = false;
119
120
// List of pools used for different auth types
121
private static final Pool[] pools = new Pool[3];
122
123
static {
124
maxSize = getInteger(MAX_POOL_SIZE, DEFAULT_MAX_POOL_SIZE);
125
126
prefSize = getInteger(PREF_POOL_SIZE, DEFAULT_PREF_POOL_SIZE);
127
128
initSize = getInteger(INIT_POOL_SIZE, DEFAULT_INIT_POOL_SIZE);
129
130
idleTimeout = getLong(POOL_TIMEOUT, DEFAULT_TIMEOUT);
131
132
// Determine supported authentication mechanisms
133
String str = getProperty(POOL_AUTH, DEFAULT_AUTH_MECHS);
134
StringTokenizer parser = new StringTokenizer(str);
135
int count = parser.countTokens();
136
String mech;
137
int p;
138
for (int i = 0; i < count; i++) {
139
mech = parser.nextToken().toLowerCase(Locale.ENGLISH);
140
if (mech.equals("anonymous")) {
141
mech = "none";
142
}
143
144
p = findPool(mech);
145
if (p >= 0 && pools[p] == null) {
146
pools[p] = new Pool(initSize, prefSize, maxSize);
147
}
148
}
149
150
// Determine supported protocols
151
str= getProperty(POOL_PROTOCOL, DEFAULT_PROTOCOLS);
152
parser = new StringTokenizer(str);
153
count = parser.countTokens();
154
String proto;
155
for (int i = 0; i < count; i++) {
156
proto = parser.nextToken();
157
if ("plain".equalsIgnoreCase(proto)) {
158
supportPlainProtocol = true;
159
} else if ("ssl".equalsIgnoreCase(proto)) {
160
supportSslProtocol = true;
161
} else {
162
// ignore
163
}
164
}
165
166
if (idleTimeout > 0) {
167
// Create cleaner to expire idle connections
168
PrivilegedAction<Void> pa = new PrivilegedAction<Void>() {
169
public Void run() {
170
Thread t = InnocuousThread.newSystemThread(
171
"LDAP PoolCleaner",
172
new PoolCleaner(idleTimeout, pools));
173
assert t.getContextClassLoader() == null;
174
t.setDaemon(true);
175
t.start();
176
return null;
177
}};
178
AccessController.doPrivileged(pa);
179
}
180
181
if (debug) {
182
showStats(System.err);
183
}
184
}
185
186
// Cannot instantiate one of these
187
private LdapPoolManager() {
188
}
189
190
/**
191
* Find the index of the pool for the specified mechanism. If not
192
* one of "none", "simple", "DIGEST-MD5", or "GSSAPI",
193
* return -1.
194
* @param mech mechanism type
195
*/
196
private static int findPool(String mech) {
197
if ("none".equalsIgnoreCase(mech)) {
198
return NONE;
199
} else if ("simple".equalsIgnoreCase(mech)) {
200
return SIMPLE;
201
} else if ("digest-md5".equalsIgnoreCase(mech)) {
202
return DIGEST;
203
}
204
return -1;
205
}
206
207
/**
208
* Determines whether pooling is allowed given information on how
209
* the connection will be used.
210
*
211
* Non-configurable rejections:
212
* - nonstandard socketFactory has been specified: the pool manager
213
* cannot track input or parameters used by the socket factory and
214
* thus has no way of determining whether two connection requests
215
* are equivalent. Maybe in the future it might add a list of allowed
216
* socket factories to be configured
217
* - trace enabled (except when debugging)
218
* - for Digest authentication, if a callback handler has been specified:
219
* the pool manager cannot track input collected by the handler
220
* and thus has no way of determining whether two connection requests are
221
* equivalent. Maybe in the future it might add a list of allowed
222
* callback handlers.
223
*
224
* Configurable tests:
225
* - Pooling for the requested protocol (plain or ssl) is supported
226
* - Pooling for the requested authentication mechanism is supported
227
*
228
*/
229
static boolean isPoolingAllowed(String socketFactory, OutputStream trace,
230
String authMech, String protocol, Hashtable<?,?> env)
231
throws NamingException {
232
233
if (trace != null && !debug
234
235
// Requesting plain protocol but it is not supported
236
|| (protocol == null && !supportPlainProtocol)
237
238
// Requesting ssl protocol but it is not supported
239
|| ("ssl".equalsIgnoreCase(protocol) && !supportSslProtocol)) {
240
241
d("Pooling disallowed due to tracing or unsupported pooling of protocol");
242
return false;
243
}
244
// pooling of custom socket factory is possible only if the
245
// socket factory interface implements java.util.comparator
246
String COMPARATOR = "java.util.Comparator";
247
boolean foundSockCmp = false;
248
if ((socketFactory != null) &&
249
!socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
250
try {
251
Class<?> socketFactoryClass = Obj.helper.loadClass(socketFactory);
252
Class<?>[] interfaces = socketFactoryClass.getInterfaces();
253
for (int i = 0; i < interfaces.length; i++) {
254
if (interfaces[i].getCanonicalName().equals(COMPARATOR)) {
255
foundSockCmp = true;
256
}
257
}
258
} catch (Exception e) {
259
CommunicationException ce =
260
new CommunicationException("Loading the socket factory");
261
ce.setRootCause(e);
262
throw ce;
263
}
264
if (!foundSockCmp) {
265
return false;
266
}
267
}
268
// Cannot use pooling if authMech is not a supported mechs
269
// Cannot use pooling if authMech contains multiple mechs
270
int p = findPool(authMech);
271
if (p < 0 || pools[p] == null) {
272
d("authmech not found: ", authMech);
273
274
return false;
275
}
276
277
d("using authmech: ", authMech);
278
279
switch (p) {
280
case NONE:
281
case SIMPLE:
282
return true;
283
284
case DIGEST:
285
// Provider won't be able to determine connection identity
286
// if an alternate callback handler is used
287
return (env == null || env.get(SASL_CALLBACK) == null);
288
}
289
return false;
290
}
291
292
/**
293
* Obtains a pooled connection that either already exists or is
294
* newly created using the parameters supplied. If it is newly
295
* created, it needs to go through the authentication checks to
296
* determine whether an LDAP bind is necessary.
297
*
298
* Caller needs to invoke ldapClient.authenticateCalled() to
299
* determine whether ldapClient.authenticate() needs to be invoked.
300
* Caller has that responsibility because caller needs to deal
301
* with the LDAP bind response, which might involve referrals,
302
* response controls, errors, etc. This method is responsible only
303
* for establishing the connection.
304
*
305
* @return an LdapClient that is pooled.
306
*/
307
static LdapClient getLdapClient(String host, int port, String socketFactory,
308
int connTimeout, int readTimeout, OutputStream trace, int version,
309
String authMech, Control[] ctls, String protocol, String user,
310
Object passwd, Hashtable<?,?> env) throws NamingException {
311
312
// Create base identity for LdapClient
313
ClientId id = null;
314
Pool pool;
315
316
int p = findPool(authMech);
317
if (p < 0 || (pool=pools[p]) == null) {
318
throw new IllegalArgumentException(
319
"Attempting to use pooling for an unsupported mechanism: " +
320
authMech);
321
}
322
switch (p) {
323
case NONE:
324
id = new ClientId(version, host, port, protocol,
325
ctls, trace, socketFactory);
326
break;
327
328
case SIMPLE:
329
// Add identity information used in simple authentication
330
id = new SimpleClientId(version, host, port, protocol,
331
ctls, trace, socketFactory, user, passwd);
332
break;
333
334
case DIGEST:
335
// Add user/passwd/realm/authzid/qop/strength/maxbuf/mutual/policy*
336
id = new DigestClientId(version, host, port, protocol,
337
ctls, trace, socketFactory, user, passwd, env);
338
break;
339
}
340
341
return (LdapClient) pool.getPooledConnection(id, connTimeout,
342
new LdapClientFactory(host, port, socketFactory, connTimeout,
343
readTimeout, trace));
344
}
345
346
public static void showStats(PrintStream out) {
347
out.println("***** start *****");
348
out.println("idle timeout: " + idleTimeout);
349
out.println("maximum pool size: " + maxSize);
350
out.println("preferred pool size: " + prefSize);
351
out.println("initial pool size: " + initSize);
352
out.println("protocol types: " + (supportPlainProtocol ? "plain " : "") +
353
(supportSslProtocol ? "ssl" : ""));
354
out.println("authentication types: " +
355
(pools[NONE] != null ? "none " : "") +
356
(pools[SIMPLE] != null ? "simple " : "") +
357
(pools[DIGEST] != null ? "DIGEST-MD5 " : ""));
358
359
for (int i = 0; i < pools.length; i++) {
360
if (pools[i] != null) {
361
out.println(
362
(i == NONE ? "anonymous pools" :
363
i == SIMPLE ? "simple auth pools" :
364
i == DIGEST ? "digest pools" : "")
365
+ ":");
366
pools[i].showStats(out);
367
}
368
}
369
out.println("***** end *****");
370
}
371
372
/**
373
* Closes idle connections idle since specified time.
374
*
375
* @param threshold Close connections idle since this time, as
376
* specified in milliseconds since "the epoch".
377
* @see java.util.Date
378
*/
379
public static void expire(long threshold) {
380
for (int i = 0; i < pools.length; i++) {
381
if (pools[i] != null) {
382
pools[i].expire(threshold);
383
}
384
}
385
}
386
387
private static void d(String msg) {
388
if (debug) {
389
System.err.println("LdapPoolManager: " + msg);
390
}
391
}
392
393
private static void d(String msg, String o) {
394
if (debug) {
395
System.err.println("LdapPoolManager: " + msg + o);
396
}
397
}
398
399
private static final String getProperty(final String propName, final String defVal) {
400
PrivilegedAction<String> pa = () -> System.getProperty(propName, defVal);
401
return AccessController.doPrivileged(pa);
402
}
403
404
private static final int getInteger(final String propName, final int defVal) {
405
PrivilegedAction<Integer> pa = () -> Integer.getInteger(propName, defVal);
406
return AccessController.doPrivileged(pa);
407
}
408
409
private static final long getLong(final String propName, final long defVal) {
410
PrivilegedAction<Long> pa = () -> Long.getLong(propName, defVal);
411
return AccessController.doPrivileged(pa);
412
}
413
}
414
415