Path: blob/master/test/jdk/com/sun/jndi/ldap/lib/BaseLdapServer.java
41155 views
/*1* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.ByteArrayOutputStream;24import java.io.Closeable;25import java.io.IOException;26import java.io.InputStream;27import java.io.OutputStream;28import java.net.InetAddress;29import java.net.ServerSocket;30import java.net.Socket;31import java.util.ArrayList;32import java.util.Arrays;33import java.util.List;34import java.util.Objects;35import java.util.concurrent.ExecutorService;36import java.util.concurrent.Executors;3738import static java.lang.System.Logger.Level.INFO;3940/*41* A bare-bones (testing aid) server for LDAP scenarios.42*43* Override the following methods to provide customized behavior44*45* * beforeAcceptingConnections46* * beforeConnectionHandled47* * handleRequest (or handleRequestEx)48*49* Instances of this class are safe for use by multiple threads.50*/51public class BaseLdapServer implements Closeable {5253private static final System.Logger logger = System.getLogger("BaseLdapServer");5455private final Thread acceptingThread = new Thread(this::acceptConnections);56private final ServerSocket serverSocket;57private final List<Socket> socketList = new ArrayList<>();58private final ExecutorService connectionsPool;5960private final Object lock = new Object();61/*62* 3-valued state to detect restarts and other programming errors.63*/64private State state = State.NEW;6566private enum State {67NEW,68STARTED,69STOPPED70}7172public BaseLdapServer() throws IOException {73this(new ServerSocket(0, 0, InetAddress.getLoopbackAddress()));74}7576public BaseLdapServer(ServerSocket serverSocket) {77this.serverSocket = Objects.requireNonNull(serverSocket);78this.connectionsPool = Executors.newCachedThreadPool();79}8081private void acceptConnections() {82logger().log(INFO, "Server is accepting connections at port {0}",83getPort());84try {85beforeAcceptingConnections();86while (isRunning()) {87Socket socket = serverSocket.accept();88logger().log(INFO, "Accepted new connection at {0}", socket);89synchronized (lock) {90// Recheck if the server is still running91// as someone has to close the `socket`92if (isRunning()) {93socketList.add(socket);94} else {95closeSilently(socket);96}97}98connectionsPool.submit(() -> handleConnection(socket));99}100} catch (Throwable t) {101if (isRunning()) {102throw new RuntimeException(103"Unexpected exception while accepting connections", t);104}105} finally {106logger().log(INFO, "Server stopped accepting connections at port {0}",107getPort());108}109}110111/*112* Called once immediately preceding the server accepting connections.113*114* Override to customize the behavior.115*/116protected void beforeAcceptingConnections() { }117118/*119* A "Template Method" describing how a connection (represented by a socket)120* is handled.121*122* The socket is closed immediately before the method returns (normally or123* abruptly).124*/125private void handleConnection(Socket socket) {126// No need to close socket's streams separately, they will be closed127// automatically when `socket.close()` is called128beforeConnectionHandled(socket);129ConnWrapper connWrapper = new ConnWrapper(socket);130try (socket) {131OutputStream out = socket.getOutputStream();132InputStream in = socket.getInputStream();133byte[] inBuffer = new byte[1024];134int count;135byte[] request;136137ByteArrayOutputStream buffer = new ByteArrayOutputStream();138int msgLen = -1;139140// As inBuffer.length > 0, at least 1 byte is read141while ((count = in.read(inBuffer)) > 0) {142buffer.write(inBuffer, 0, count);143if (msgLen <= 0) {144msgLen = LdapMessage.getMessageLength(buffer.toByteArray());145}146147if (msgLen > 0 && buffer.size() >= msgLen) {148if (buffer.size() > msgLen) {149byte[] tmpBuffer = buffer.toByteArray();150request = Arrays.copyOf(tmpBuffer, msgLen);151buffer.reset();152buffer.write(tmpBuffer, msgLen, tmpBuffer.length - msgLen);153} else {154request = buffer.toByteArray();155buffer.reset();156}157msgLen = -1;158} else {159logger.log(INFO, "Request message incomplete, " +160"bytes received {0}, expected {1}", buffer.size(), msgLen);161continue;162}163handleRequestEx(socket, new LdapMessage(request), out, connWrapper);164if (connWrapper.updateRequired()) {165var wrapper = connWrapper.getWrapper();166in = wrapper.getInputStream();167out = wrapper.getOutputStream();168connWrapper.clearFlag();169}170}171} catch (Throwable t) {172if (!isRunning()) {173logger.log(INFO, "Connection Handler exit {0}", t.getMessage());174} else {175t.printStackTrace();176}177}178179if (connWrapper.getWrapper() != null) {180closeSilently(connWrapper.getWrapper());181}182}183184/*185* Called first thing in `handleConnection()`.186*187* Override to customize the behavior.188*/189protected void beforeConnectionHandled(Socket socket) { /* empty */ }190191/*192* Called after an LDAP request has been read in `handleConnection()`.193*194* Override to customize the behavior.195*/196protected void handleRequest(Socket socket,197LdapMessage request,198OutputStream out)199throws IOException200{201logger().log(INFO, "Discarding message {0} from {1}. "202+ "Override {2}.handleRequest to change this behavior.",203request, socket, getClass().getName());204}205206/*207* Called after an LDAP request has been read in `handleConnection()`.208*209* Override to customize the behavior if you want to handle starttls210* extended op, otherwise override handleRequest method instead.211*212* This is extended handleRequest method which provide possibility to213* wrap current socket connection, that's necessary to handle starttls214* extended request, here is sample code about how to wrap current socket215*216* switch (request.getOperation()) {217* ......218* case EXTENDED_REQUEST:219* if (new String(request.getMessage()).endsWith(STARTTLS_REQ_OID)) {220* out.write(STARTTLS_RESPONSE);221* SSLSocket sslSocket = (SSLSocket) sslSocketFactory222* .createSocket(socket, null, socket.getLocalPort(),223* false);224* sslSocket.setUseClientMode(false);225* connWrapper.setWrapper(sslSocket);226* }227* break;228* ......229* }230*/231protected void handleRequestEx(Socket socket,232LdapMessage request,233OutputStream out,234ConnWrapper connWrapper)235throws IOException {236// by default, just call handleRequest to keep compatibility237handleRequest(socket, request, out);238}239240/*241* To be used by subclasses.242*/243protected final System.Logger logger() {244return logger;245}246247/*248* Starts this server. May be called only once.249*/250public BaseLdapServer start() {251synchronized (lock) {252if (state != State.NEW) {253throw new IllegalStateException(state.toString());254}255state = State.STARTED;256logger().log(INFO, "Starting server at port {0}", getPort());257acceptingThread.start();258return this;259}260}261262/*263* Stops this server.264*265* May be called at any time, even before a call to `start()`. In the latter266* case the subsequent call to `start()` will throw an exception. Repeated267* calls to this method have no effect.268*269* Stops accepting new connections, interrupts the threads serving already270* accepted connections and closes all the sockets.271*/272@Override273public void close() {274synchronized (lock) {275if (state == State.STOPPED) {276return;277}278state = State.STOPPED;279logger().log(INFO, "Stopping server at port {0}", getPort());280acceptingThread.interrupt();281closeSilently(serverSocket);282// It's important to signal an interruption so that overridden283// methods have a chance to return if they use284// interruption-sensitive blocking operations. However, blocked I/O285// operations on the socket will NOT react on that, hence the socket286// also has to be closed to propagate shutting down.287connectionsPool.shutdownNow();288socketList.forEach(BaseLdapServer.this::closeSilently);289}290}291292/**293* Returns the local port this server is listening at.294*295* This method can be called at any time.296*297* @return the port this server is listening at298*/299public int getPort() {300return serverSocket.getLocalPort();301}302303/**304* Returns the address this server is listening at.305*306* This method can be called at any time.307*308* @return the address309*/310public InetAddress getInetAddress() {311return serverSocket.getInetAddress();312}313314/*315* Returns a flag to indicate whether this server is running or not.316*317* @return {@code true} if this server is running, {@code false} otherwise.318*/319public boolean isRunning() {320synchronized (lock) {321return state == State.STARTED;322}323}324325/*326* To be used by subclasses.327*/328protected final void closeSilently(Closeable resource) {329try {330resource.close();331} catch (IOException ignored) { }332}333334/*335* To be used for handling starttls extended request336*/337protected class ConnWrapper {338private Socket original;339private Socket wrapper;340private boolean flag = false;341342public ConnWrapper(Socket socket) {343original = socket;344}345346public Socket getWrapper() {347return wrapper;348}349350public void setWrapper(Socket wrapper) {351if (wrapper != null && wrapper != original) {352this.wrapper = wrapper;353flag = true;354}355}356357public boolean updateRequired() {358return flag;359}360361public void clearFlag() {362flag = false;363}364}365}366367368