Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/com/sun/jndi/ldap/LdapDnsProviderTest.java
41153 views
1
/*
2
* Copyright (c) 2018, 2020, 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
import java.io.File;
27
import java.io.FileOutputStream;
28
import java.io.IOException;
29
import java.security.Permission;
30
import java.util.HashSet;
31
import java.util.Hashtable;
32
import java.util.Random;
33
import java.util.Set;
34
import java.util.concurrent.Callable;
35
import java.util.concurrent.ExecutionException;
36
import java.util.concurrent.FutureTask;
37
38
import javax.naming.Context;
39
import javax.naming.InitialContext;
40
import javax.naming.NamingException;
41
import javax.naming.directory.InitialDirContext;
42
import javax.naming.directory.SearchControls;
43
44
import sun.net.PortConfig;
45
46
import jdk.test.lib.RandomFactory;
47
48
/**
49
* @test
50
* @bug 8160768
51
* @key randomness intermittent
52
* @summary ctx provider tests for ldap.
53
* Two test cases need to establish connection to the
54
* unreachable port on localhost. Each tries 5 connection
55
* attempts with a random port expecting for connection to fail.
56
* In rare cases it could establish connections due to services
57
* running on these ports, therefore it can fail intermittently.
58
* @modules java.naming/com.sun.jndi.ldap java.base/sun.net
59
* @library /test/lib
60
* @build jdk.test.lib.RandomFactory
61
* @compile dnsprovider/TestDnsProvider.java
62
* @run main/othervm LdapDnsProviderTest
63
* @run main/othervm LdapDnsProviderTest nosm
64
* @run main/othervm -Djava.security.manager=allow LdapDnsProviderTest smnodns
65
* @run main/othervm -Djava.security.manager=allow LdapDnsProviderTest smdns
66
* @run main/othervm LdapDnsProviderTest nosmbaddns
67
*/
68
69
class DNSSecurityManager extends SecurityManager {
70
71
private boolean dnsProvider = false;
72
73
public void setAllowDnsProvider(boolean allow) {
74
dnsProvider = allow;
75
}
76
77
@Override
78
public void checkPermission(Permission p) {
79
if (p.getName().equals("ldapDnsProvider") && !dnsProvider) {
80
throw new SecurityException(p.getName());
81
}
82
}
83
}
84
85
class ProviderTest implements Callable<Boolean> {
86
87
private final String url;
88
private final String expected;
89
private final Hashtable<String, String> env = new Hashtable<>(11);
90
91
public ProviderTest(String url, String expected) {
92
this.url = url;
93
this.expected = expected;
94
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
95
}
96
97
boolean shutItDown(InitialContext ctx) {
98
try {
99
if (ctx != null) ctx.close();
100
return true;
101
} catch (NamingException ex) {
102
return false;
103
}
104
}
105
106
public Boolean call() {
107
boolean passed;
108
InitialContext ctx = null;
109
110
if (url != null) {
111
env.put(Context.PROVIDER_URL, url);
112
}
113
114
// Set JNDI LDAP connect timeout property. It helps to prevent
115
// initial bind operation from blocking in case of a local process
116
// listening on the port specified in the URL. With the property set,
117
// the bind operation will fail with timeout exception, and then it
118
// could be retried with another port number.
119
env.put("com.sun.jndi.ldap.connect.timeout", "1000");
120
121
try {
122
ctx = new InitialDirContext(env);
123
SearchControls scl = new SearchControls();
124
scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
125
((InitialDirContext)ctx).search(
126
"ou=People,o=Test", "(objectClass=*)", scl);
127
throw new RuntimeException("Search should not complete");
128
} catch (NamingException e) {
129
passed = e.toString().contains(expected);
130
System.err.println((passed ? "Expected" : "Unexpected") +
131
" NamingException observed: " + e.toString());
132
// Print stack trace only for unexpected exceptions
133
if (!passed) {
134
e.printStackTrace();
135
}
136
} finally {
137
shutItDown(ctx);
138
}
139
return passed;
140
}
141
}
142
143
public class LdapDnsProviderTest {
144
145
private static final String TEST_CLASSES =
146
System.getProperty("test.classes", ".");
147
148
public static void writeFile(String content, File dstFile)
149
throws IOException
150
{
151
try (FileOutputStream dst = new FileOutputStream(dstFile)) {
152
byte[] buf = content.getBytes();
153
dst.write(buf, 0, buf.length);
154
}
155
}
156
157
public static void installServiceConfigurationFile(String content) {
158
String filename = "javax.naming.ldap.spi.LdapDnsProvider";
159
160
File dstDir = new File(TEST_CLASSES, "META-INF/services");
161
if (!dstDir.exists()) {
162
if (!dstDir.mkdirs()) {
163
throw new RuntimeException(
164
"could not create META-INF/services directory " + dstDir);
165
}
166
}
167
File dstFile = new File(dstDir, filename);
168
169
try {
170
writeFile(content, dstFile);
171
} catch (IOException e) {
172
throw new RuntimeException("could not install " + dstFile, e);
173
}
174
}
175
176
public static void main(String[] args) throws Exception {
177
if (args.length > 0 && args[0].equals("nosm")) {
178
// no security manager, serviceloader
179
installServiceConfigurationFile("dnsprovider.TestDnsProvider");
180
runTest("ldap:///dc=example,dc=com", "yupyupyup:389");
181
} else if (args.length > 0 && args[0].equals("smnodns")) {
182
// security manager & serviceloader
183
installServiceConfigurationFile("dnsprovider.TestDnsProvider");
184
// install security manager
185
System.setSecurityManager(new DNSSecurityManager());
186
runTest("ldap:///dc=example,dc=com", "ServiceConfigurationError");
187
} else if (args.length > 0 && args[0].equals("smdns")) {
188
// security manager & serviceloader
189
DNSSecurityManager sm = new DNSSecurityManager();
190
installServiceConfigurationFile("dnsprovider.TestDnsProvider");
191
// install security manager
192
System.setSecurityManager(sm);
193
sm.setAllowDnsProvider(true);
194
runTest("ldap:///dc=example,dc=com", "yupyupyup:389");
195
} else if (args.length > 0 && args[0].equals("nosmbaddns")) {
196
// no security manager, no serviceloader
197
// DefaultLdapDnsProvider
198
installServiceConfigurationFile("dnsprovider.MissingDnsProvider");
199
// no SecurityManager
200
runTest("ldap:///dc=example,dc=com", "not found");
201
} else {
202
// no security manager, no serviceloader
203
// DefaultLdapDnsProvider
204
System.err.println("TEST_CLASSES:");
205
System.err.println(TEST_CLASSES);
206
File f = new File(
207
TEST_CLASSES, "META-INF/services/javax.naming.ldap.spi.LdapDnsProvider");
208
if (f.exists()) {
209
f.delete();
210
}
211
212
// no SecurityManager
213
runTest("ldap:///dc=example,dc=com", "localhost:389");
214
runTest("ldap://localhost/dc=example,dc=com", "localhost:389");
215
runLocalHostTestWithRandomPort("ldap", "/dc=example,dc=com", 5);
216
runLocalHostTestWithRandomPort("ldaps", "/dc=example,dc=com", 5);
217
runTest("ldaps://localhost/dc=example,dc=com", "localhost:636");
218
runTest(null, "localhost:389");
219
runTest("", "ConfigurationException");
220
}
221
}
222
223
// Pseudorandom number generator
224
private static final Random RND = RandomFactory.getRandom();
225
// Port numbers already seen to be generated by pseudorandom generator
226
private static final Set<Integer> SEEN_PORTS = new HashSet<>();
227
228
// Get random, previously unseen port number from [1111, PortConfig.getUpper()) range
229
private static int generateUnseenPort() {
230
int port;
231
do {
232
port = 1111 + RND.nextInt(PortConfig.getUpper() - 1111);
233
// Seen ports will never contain more than maxAttempts*2 ports
234
} while (SEEN_PORTS.contains(port));
235
SEEN_PORTS.add(port);
236
return port;
237
}
238
239
// Run test with ldap connection to localhost and random port. The test is expected to fail
240
// with CommunicationException that is caused by connection refuse exception.
241
// But in case if there is a service running on the same port the connection
242
// will be established and then closed or timed-out. Both cases will generate exception
243
// messages which differ from the expected one.
244
// For such cases the test will be repeated with another random port. That will be done
245
// maxAttempts times. If the expected exception won't be observed - test will be treated
246
// as failed.
247
private static void runLocalHostTestWithRandomPort(String scheme, String path, int maxAttempts) {
248
for (int attempt = 0; attempt <= maxAttempts; attempt++) {
249
boolean attemptSuccessful = true;
250
int port = generateUnseenPort();
251
252
// Construct URL for the current attempt
253
String url = scheme + "://localhost" + ":" + port + path;
254
255
// Construct text expected to be present in Exception message
256
String expected = "localhost:" + port;
257
258
System.err.printf("Iteration %d: Testing: url='%s', expected content='%s'%n",
259
attempt, url, expected);
260
261
FutureTask<Boolean> future = new FutureTask<>(
262
new ProviderTest(url, expected));
263
new Thread(future).start();
264
while (!future.isDone()) {
265
try {
266
if (!future.get()) {
267
if (attempt == maxAttempts) {
268
throw new RuntimeException("Test failed, ProviderTest" +
269
" returned false " + maxAttempts + " times");
270
} else {
271
System.err.printf("Iteration %d failed:" +
272
" ProviderTest returned false%n", attempt);
273
attemptSuccessful = false;
274
}
275
}
276
} catch (InterruptedException | ExecutionException e) {
277
System.err.println("Iteration %d failed to execute provider test: " + e.getMessage());
278
attemptSuccessful = false;
279
}
280
}
281
if (attemptSuccessful) {
282
System.err.println("Test passed. It took " + (attempt + 1) + " iterations to complete");
283
break;
284
}
285
}
286
}
287
288
private static void runTest(String url, String expected) {
289
FutureTask<Boolean> future =
290
new FutureTask<>(
291
new ProviderTest(url, expected));
292
new Thread(future).start();
293
294
System.err.printf("Testing: url='%s', expected content='%s'%n", url, expected);
295
while (!future.isDone()) {
296
try {
297
if (!future.get()) {
298
System.err.println("Test failed");
299
throw new RuntimeException(
300
"Test failed, ProviderTest returned false");
301
}
302
} catch (Exception e) {
303
if (!e.toString().contains(expected)) {
304
System.err.println("Test failed");
305
throw new RuntimeException(
306
"Test failed, unexpected result");
307
}
308
}
309
}
310
System.err.println("Test passed");
311
}
312
313
}
314
315
316