author | xyin |
Mon, 06 May 2019 14:23:32 +0800 | |
branch | JDK-8210696-branch |
changeset 57351 | b9e5f8090688 |
parent 57346 | 3efc6cb7ffdb |
permissions | -rw-r--r-- |
57345 | 1 |
/* |
2 |
* Copyright (c) 2019, 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. |
|
8 |
* |
|
9 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
10 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
11 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
12 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
13 |
* accompanied this code). |
|
14 |
* |
|
15 |
* You should have received a copy of the GNU General Public License version |
|
16 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
17 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
18 |
* |
|
19 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
20 |
* or visit www.oracle.com if you need additional information or have any |
|
21 |
* questions. |
|
22 |
*/ |
|
23 |
||
24 |
import java.io.ByteArrayOutputStream; |
|
25 |
import java.io.Closeable; |
|
26 |
import java.io.IOException; |
|
27 |
import java.io.InputStream; |
|
28 |
import java.io.OutputStream; |
|
29 |
import java.net.InetAddress; |
|
30 |
import java.net.ServerSocket; |
|
31 |
import java.net.Socket; |
|
32 |
import java.util.ArrayList; |
|
33 |
import java.util.Arrays; |
|
34 |
import java.util.HashSet; |
|
35 |
import java.util.List; |
|
36 |
import java.util.Objects; |
|
37 |
import java.util.Set; |
|
38 |
import java.util.concurrent.ExecutorService; |
|
39 |
import java.util.concurrent.Executors; |
|
40 |
import java.util.concurrent.RejectedExecutionException; |
|
41 |
import java.util.concurrent.ThreadFactory; |
|
42 |
import java.util.concurrent.TimeUnit; |
|
43 |
import java.util.stream.Stream; |
|
44 |
||
45 |
import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE; |
|
46 |
||
47 |
/** |
|
48 |
* A base dummy ldap server. |
|
49 |
* |
|
50 |
* For any ldap tests which required a simple dummy server to support the |
|
51 |
* test, may use this server directly with specifying ConnectionHandler, |
|
52 |
* SessionHandler/RequestHandler, or extends to build more complex server logic. |
|
53 |
* |
|
54 |
* This server already extends Thread and implements AutoCloseable, so it can |
|
55 |
* be started in thread and integrated with try-with-resources |
|
56 |
* |
|
57 |
* To initiate a instance of this server, valid ServerSocket could be supplied, |
|
58 |
* it will allow the flexibility for listening address/port customization |
|
59 |
* and SSL usage, for default no parameter constructor, a ServerSocket which |
|
60 |
* listen on loopback address will be created. |
|
61 |
* |
|
62 |
* To use this dummy server in test, user could customize the processing logic |
|
63 |
* in three level with below handler interface. |
|
64 |
* -ConnectionHandler provide connection level handling, server will hand |
|
65 |
* over accepted socket and processing thread to handler. |
|
66 |
* By default, DefaultConnectionHandler will be used if no |
|
67 |
* specified, it reads full ldap request message then |
|
68 |
* pass it to RequestHandler instance which returned by |
|
69 |
* SessionHandler per session. |
|
70 |
* |
|
71 |
* -SessionHandler provide session level handling when DefaultConnectionHandler |
|
72 |
* been used, it's to retrieve RequestHandler instance of |
|
73 |
* current session. |
|
74 |
* For most of tests, only one session need to be handled |
|
75 |
* on server or all ldap request could be handled by same |
|
76 |
* logic whatever current session is, user can use |
|
77 |
* setCommonRequestHandler to setup one single session |
|
78 |
* handler which will always return given RequestHandler |
|
79 |
* instance. |
|
80 |
* |
|
81 |
* -RequestHandler provide ldap message request handling when |
|
82 |
* DefaultConnectionHandler been used. |
|
83 |
* |
|
84 |
* @see ConnectionHandler |
|
85 |
* @see SessionHandler |
|
86 |
* @see RequestHandler |
|
87 |
*/ |
|
88 |
public class BaseLdapServer extends Thread implements AutoCloseable { |
|
89 |
private volatile boolean isRunning; |
|
90 |
private final List<Socket> socketList = new ArrayList<>(); |
|
91 |
private ServerSocket serverSocket; |
|
92 |
private ExecutorService workingPool; |
|
93 |
private ConnectionHandler connectionHandler; |
|
94 |
private SessionHandler sessionHandler; |
|
95 |
||
96 |
enum DebugLevel { |
|
97 |
FULL, // all debug message will be printed |
|
98 |
NONE, // none of debug message will be printed |
|
99 |
CUSTOMIZE // only specified class debug message will be printed |
|
100 |
} |
|
101 |
||
102 |
private StackWalker stackWalker = null; |
|
103 |
private DebugLevel debugLevel = DebugLevel.NONE; |
|
104 |
private Set<Class<?>> debugOptions = new HashSet<>(); |
|
105 |
||
106 |
/** |
|
107 |
* BaseLdapServer overload default constructor. |
|
108 |
* |
|
109 |
* @throws IOException if an I/O error occurs when opening the socket. |
|
110 |
*/ |
|
111 |
public BaseLdapServer() throws IOException { |
|
112 |
this(new ServerSocket(0, 0, InetAddress.getLoopbackAddress())); |
|
113 |
} |
|
114 |
||
115 |
/** |
|
116 |
* BaseLdapServer constructor with given server socket and specify whether |
|
117 |
* use daemon for each accept connection handling thread. |
|
118 |
* |
|
119 |
* @param serverSocket given server socket |
|
120 |
*/ |
|
57346 | 121 |
public BaseLdapServer(ServerSocket serverSocket) { |
57345 | 122 |
this.serverSocket = Objects.requireNonNull(serverSocket); |
57346 | 123 |
workingPool = Executors.newCachedThreadPool(); |
57345 | 124 |
try { |
125 |
stackWalker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE); |
|
126 |
} catch (SecurityException se) { |
|
127 |
// just ignore |
|
128 |
} |
|
129 |
} |
|
130 |
||
131 |
@Override |
|
132 |
public void run() { |
|
133 |
if (getConnectionHandler() == null) { |
|
134 |
debug("INFO: No connection handler been specified, try default."); |
|
135 |
connectionHandler = new DefaultConnectionHandler(); |
|
136 |
} |
|
137 |
debug("INFO: Using connection handler : " + getConnectionHandler() |
|
138 |
.getClass().getName()); |
|
139 |
debug("INFO: LdapServer running and listening on port " + getPort()); |
|
140 |
try { |
|
141 |
while (isRunning) { |
|
142 |
Socket socket = serverSocket.accept(); |
|
143 |
debug("INFO: Accept new connection " + socket); |
|
144 |
synchronized (socketList) { |
|
145 |
socketList.add(socket); |
|
146 |
} |
|
147 |
workingPool.submit(() -> getConnectionHandler() |
|
148 |
.handleConnection(socket)); |
|
149 |
} |
|
150 |
} catch (IOException | RejectedExecutionException e) { |
|
151 |
if (isRunning) { |
|
152 |
throw new RuntimeException(e); |
|
153 |
} else { |
|
154 |
debug("INFO: Server exit."); |
|
155 |
} |
|
156 |
} |
|
157 |
} |
|
158 |
||
159 |
/* |
|
160 |
* Override Thread.start() |
|
161 |
*/ |
|
162 |
@Override |
|
163 |
public synchronized void start() { |
|
57351
b9e5f8090688
JDK-8210696-branch: fix loadCaptureFile exception swallowing
xyin
parents:
57346
diff
changeset
|
164 |
isRunning = true; |
57345 | 165 |
super.start(); |
166 |
} |
|
167 |
||
168 |
/** |
|
169 |
* Start Server thread and return itself for method chaining |
|
170 |
* |
|
171 |
* @return current server instance |
|
172 |
*/ |
|
173 |
@SuppressWarnings("unchecked") |
|
174 |
public <T extends BaseLdapServer> T startServer() { |
|
175 |
start(); |
|
176 |
return (T) this; |
|
177 |
} |
|
178 |
||
179 |
/** |
|
180 |
* Stop server. |
|
181 |
*/ |
|
182 |
public void stopServer() { |
|
183 |
debug("INFO: Stopping Server."); |
|
184 |
isRunning = false; |
|
185 |
workingPool.shutdown(); |
|
186 |
cleanupClosableRes(serverSocket); |
|
57346 | 187 |
// let's cleanup thread pool |
188 |
synchronized (socketList) { |
|
189 |
socketList.forEach(BaseLdapServer::cleanupClosableRes); |
|
190 |
} |
|
191 |
try { |
|
192 |
if (!workingPool.awaitTermination(10, TimeUnit.SECONDS)) { |
|
193 |
workingPool.shutdownNow(); |
|
57345 | 194 |
} |
57346 | 195 |
} catch (InterruptedException e) { |
196 |
workingPool.shutdownNow(); |
|
197 |
Thread.currentThread().interrupt(); |
|
57345 | 198 |
} |
199 |
} |
|
200 |
||
201 |
/** |
|
202 |
* Return local port which server is listening. |
|
203 |
* |
|
204 |
* @return port which server is listening |
|
205 |
*/ |
|
206 |
public int getPort() { |
|
207 |
if (serverSocket != null) { |
|
208 |
return serverSocket.getLocalPort(); |
|
209 |
} else { |
|
210 |
return -1; |
|
211 |
} |
|
212 |
} |
|
213 |
||
214 |
/** |
|
215 |
* Return flag to indicate whether current server is running. |
|
216 |
* |
|
217 |
* @return <tt>true</tt> if current server is running. |
|
218 |
*/ |
|
219 |
public boolean isRunning() { |
|
220 |
return isRunning; |
|
221 |
} |
|
222 |
||
223 |
/** |
|
224 |
* Return ConnectionHandler instance |
|
225 |
* |
|
226 |
* @return ConnectionHandler instance |
|
227 |
* @see ConnectionHandler |
|
228 |
*/ |
|
229 |
ConnectionHandler getConnectionHandler() { |
|
230 |
return connectionHandler; |
|
231 |
} |
|
232 |
||
233 |
/** |
|
234 |
* Set ConnectionHandler when server is not running. |
|
235 |
* |
|
236 |
* @param connHandler ConnectionHandler instance |
|
237 |
* @return current server instance for method chaining |
|
238 |
*/ |
|
239 |
@SuppressWarnings("unchecked") |
|
240 |
public <T extends BaseLdapServer> T setConnectionHandler( |
|
241 |
ConnectionHandler connHandler) { |
|
242 |
if (!isRunning) { |
|
243 |
connectionHandler = connHandler; |
|
244 |
} |
|
245 |
||
246 |
return (T) this; |
|
247 |
} |
|
248 |
||
249 |
/** |
|
250 |
* Return SessionHandler instance |
|
251 |
* |
|
252 |
* @return SessionHandler instance |
|
253 |
* @see SessionHandler |
|
254 |
*/ |
|
255 |
SessionHandler getSessionHandler() { |
|
256 |
return sessionHandler; |
|
257 |
} |
|
258 |
||
259 |
/** |
|
260 |
* Set SessionHandler when server is not running. |
|
261 |
* |
|
262 |
* @param sessionHandler given SessionHandler |
|
263 |
* @return current server instance for method chaining |
|
264 |
*/ |
|
265 |
@SuppressWarnings("unchecked") |
|
266 |
public <T extends BaseLdapServer> T setSessionHandler( |
|
267 |
SessionHandler sessionHandler) { |
|
268 |
if (!isRunning) { |
|
269 |
this.sessionHandler = sessionHandler; |
|
270 |
} |
|
271 |
||
272 |
return (T) this; |
|
273 |
} |
|
274 |
||
275 |
/** |
|
276 |
* Set one common RequestHandler, it will be used to handle all requests |
|
277 |
* whatever current session is. |
|
278 |
* |
|
279 |
* For most of tests, server only need to handle one session, use this |
|
280 |
* method will create stateless session handler with given request handler. |
|
281 |
* |
|
282 |
* @param requestHandler RequestHandler instance |
|
283 |
* @return current server instance for method chaining |
|
284 |
*/ |
|
285 |
@SuppressWarnings("unchecked") |
|
286 |
public <T extends BaseLdapServer> T setCommonRequestHandler( |
|
287 |
RequestHandler requestHandler) { |
|
288 |
if (!isRunning) { |
|
289 |
// ignore any session, always return fixed request handler |
|
290 |
setSessionHandler(socket -> requestHandler); |
|
291 |
} |
|
292 |
||
293 |
return (T) this; |
|
294 |
} |
|
295 |
||
296 |
@Override |
|
297 |
public void close() { |
|
298 |
stopServer(); |
|
299 |
} |
|
300 |
||
301 |
/** |
|
302 |
* Cleanup any given closable resource |
|
303 |
* |
|
304 |
* @param res given closable resource |
|
305 |
*/ |
|
306 |
static void cleanupClosableRes(Closeable res) { |
|
307 |
if (res != null) { |
|
308 |
try { |
|
309 |
res.close(); |
|
310 |
} catch (IOException e) { |
|
311 |
// ignore |
|
312 |
} |
|
313 |
} |
|
314 |
} |
|
315 |
||
316 |
/** |
|
317 |
* Set debug level to specify which kinds of debug message will be printed. |
|
318 |
* |
|
319 |
* @param debugLevel given debug level |
|
320 |
* @param opts given opts if debug level is DebugLevel.CUSTOMIZE |
|
321 |
* @return current server instance for method chaining |
|
322 |
*/ |
|
323 |
@SuppressWarnings("unchecked") |
|
324 |
public <T extends BaseLdapServer> T setDebugLevel(DebugLevel debugLevel, |
|
325 |
Class<?>... opts) { |
|
326 |
Objects.requireNonNull(debugLevel); |
|
327 |
if (!isRunning) { |
|
328 |
this.debugLevel = debugLevel; |
|
329 |
if (debugLevel == DebugLevel.CUSTOMIZE) { |
|
330 |
debugOptions.clear(); |
|
331 |
Stream.of(opts).filter(Objects::nonNull) |
|
332 |
.forEach(debugOptions::add); |
|
333 |
} |
|
334 |
} |
|
335 |
||
336 |
return (T) this; |
|
337 |
} |
|
338 |
||
339 |
/** |
|
340 |
* Print given message if debug enabled. |
|
341 |
* |
|
342 |
* @param message given message to print |
|
343 |
*/ |
|
344 |
void debug(String message) { |
|
345 |
switch (debugLevel) { |
|
346 |
case FULL: |
|
347 |
System.out.println((stackWalker != null ? |
|
348 |
stackWalker.getCallerClass().getName() : |
|
349 |
"") + ": " + message); |
|
350 |
break; |
|
351 |
case CUSTOMIZE: |
|
352 |
if (stackWalker != null) { |
|
353 |
if (debugOptions.contains(stackWalker.getCallerClass())) { |
|
354 |
System.out.println( |
|
355 |
stackWalker.getCallerClass().getName() + ": " |
|
356 |
+ message); |
|
357 |
} |
|
358 |
} |
|
359 |
break; |
|
360 |
case NONE: |
|
361 |
default: |
|
362 |
break; |
|
363 |
} |
|
364 |
} |
|
365 |
||
366 |
/** |
|
367 |
* Default connection handler implementation. |
|
368 |
*/ |
|
369 |
class DefaultConnectionHandler implements ConnectionHandler { |
|
370 |
@Override |
|
371 |
public void handleConnection(Socket socket) { |
|
372 |
try (socket; |
|
373 |
OutputStream out = socket.getOutputStream(); |
|
374 |
InputStream in = socket.getInputStream()) { |
|
375 |
byte[] inBuffer = new byte[1024]; |
|
376 |
int count; |
|
377 |
byte[] request; |
|
378 |
||
379 |
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); |
|
380 |
int msgLen = -1; |
|
381 |
||
382 |
while ((count = in.read(inBuffer)) > 0) { |
|
383 |
buffer.write(inBuffer, 0, count); |
|
384 |
if (msgLen <= 0) { |
|
385 |
msgLen = getMessageLength(buffer.toByteArray()); |
|
386 |
} |
|
387 |
||
388 |
if (msgLen > 0 && buffer.size() >= msgLen) { |
|
389 |
if (buffer.size() > msgLen) { |
|
390 |
byte[] tmpBuffer = buffer.toByteArray(); |
|
391 |
request = Arrays.copyOf(tmpBuffer, msgLen); |
|
392 |
buffer.reset(); |
|
393 |
buffer.write(tmpBuffer, msgLen, |
|
394 |
tmpBuffer.length - msgLen); |
|
395 |
} else { |
|
396 |
request = buffer.toByteArray(); |
|
397 |
buffer.reset(); |
|
398 |
} |
|
399 |
msgLen = -1; |
|
400 |
} else { |
|
401 |
debug("INFO: request msg not complete, received " |
|
402 |
+ buffer.size() + ", expected " + msgLen); |
|
403 |
continue; |
|
404 |
} |
|
405 |
||
406 |
if (getSessionHandler() != null) { |
|
407 |
var handler = getSessionHandler() |
|
408 |
.getRequestHandler(socket); |
|
409 |
if (handler != null) { |
|
410 |
debug("INFO: Process request. Session handler : " |
|
411 |
+ getSessionHandler() |
|
412 |
+ ", Request handler : " + handler); |
|
413 |
handler.handleRequest(new LdapMessage(request), |
|
414 |
out); |
|
415 |
} else { |
|
416 |
debug("WARNING: no valid request handler returned from " |
|
417 |
+ getSessionHandler() + ", " + socket); |
|
418 |
} |
|
419 |
} else { |
|
420 |
debug("WARNING: no valid session handler been specified, discard request."); |
|
421 |
} |
|
422 |
} |
|
423 |
debug("INFO: Connection Handler exit."); |
|
424 |
} catch (IOException e) { |
|
425 |
if (!isRunning()) { |
|
426 |
debug("INFO: Connection Handler exit : " + e.getMessage()); |
|
427 |
} else { |
|
428 |
e.printStackTrace(); |
|
429 |
} |
|
430 |
} |
|
431 |
} |
|
432 |
||
433 |
private int getMessageLength(byte[] encoding) { |
|
434 |
if (encoding.length < 2) { |
|
435 |
// no enough data to extract msg len, just return -1 |
|
436 |
return -1; |
|
437 |
} |
|
438 |
||
439 |
if (encoding[0] != 0x30) { |
|
440 |
throw new RuntimeException("Error: bad LDAP encoding message: " |
|
441 |
+ "expected ASN.1 SEQUENCE tag (0x30), encountered " |
|
442 |
+ encoding[0]); |
|
443 |
} |
|
444 |
||
445 |
int len; |
|
446 |
int index = 1; |
|
447 |
int payloadLen = 0; |
|
448 |
||
449 |
if ((encoding[1] & 0x80) == 0x80) { |
|
450 |
len = (encoding[1] & 0x0F); |
|
451 |
index++; |
|
452 |
} else { |
|
453 |
len = 1; |
|
454 |
} |
|
455 |
||
456 |
if (len > 4) { |
|
457 |
throw new RuntimeException( |
|
458 |
"Error: LDAP encoding message payload too large"); |
|
459 |
} |
|
460 |
||
461 |
if (encoding.length < index + len) { |
|
462 |
// additional data required to extract payload len, return -1 |
|
463 |
return -1; |
|
464 |
} |
|
465 |
||
466 |
for (byte b : Arrays.copyOfRange(encoding, index, index + len)) { |
|
467 |
payloadLen = payloadLen << 8 | (b & 0xFF); |
|
468 |
} |
|
469 |
||
470 |
if (payloadLen <= 0) { |
|
471 |
throw new RuntimeException( |
|
472 |
"Error: invalid LDAP encoding message length or payload too large"); |
|
473 |
} |
|
474 |
||
475 |
return index + len + payloadLen; |
|
476 |
} |
|
477 |
} |
|
478 |
} |