use of com.unboundid.util.MinimalLogFormatter in project ldapsdk by pingidentity.
the class LDAPDebugger method doToolProcessing.
/**
* Performs the actual processing for this tool. In this case, it gets a
* connection to the directory server and uses it to perform the requested
* search.
*
* @return The result code for the processing that was performed.
*/
@Override()
@NotNull()
public ResultCode doToolProcessing() {
// Create the proxy request handler that will be used to forward requests to
// a remote directory.
final ProxyRequestHandler proxyHandler;
try {
proxyHandler = new ProxyRequestHandler(createServerSet());
} catch (final LDAPException le) {
err("Unable to prepare to connect to the target server: ", le.getMessage());
return le.getResultCode();
}
// Create the log handler to use for the output.
final Handler logHandler;
if (outputFile.isPresent()) {
try {
logHandler = new FileHandler(outputFile.getValue().getAbsolutePath());
} catch (final IOException ioe) {
err("Unable to open the output file for writing: ", StaticUtils.getExceptionMessage(ioe));
return ResultCode.LOCAL_ERROR;
}
} else {
logHandler = new ConsoleHandler();
}
StaticUtils.setLogHandlerLevel(logHandler, Level.INFO);
logHandler.setFormatter(new MinimalLogFormatter(MinimalLogFormatter.DEFAULT_TIMESTAMP_FORMAT, false, false, true));
// Create the debugger request handler that will be used to write the
// debug output.
LDAPListenerRequestHandler requestHandler = new LDAPDebuggerRequestHandler(logHandler, proxyHandler);
// handler to accomplish that.
if (codeLogFile.isPresent()) {
try {
requestHandler = new ToCodeRequestHandler(codeLogFile.getValue(), true, requestHandler);
} catch (final Exception e) {
err("Unable to open code log file '", codeLogFile.getValue().getAbsolutePath(), "' for writing: ", StaticUtils.getExceptionMessage(e));
return ResultCode.LOCAL_ERROR;
}
}
// Create and start the LDAP listener.
final LDAPListenerConfig config = new LDAPListenerConfig(listenPort.getValue(), requestHandler);
if (listenAddress.isPresent()) {
try {
config.setListenAddress(LDAPConnectionOptions.DEFAULT_NAME_RESOLVER.getByName(listenAddress.getValue()));
} catch (final Exception e) {
err("Unable to resolve '", listenAddress.getValue(), "' as a valid address: ", StaticUtils.getExceptionMessage(e));
return ResultCode.PARAM_ERROR;
}
}
if (listenUsingSSL.isPresent()) {
try {
final SSLUtil sslUtil;
if (generateSelfSignedCertificate.isPresent()) {
final ObjectPair<File, char[]> keyStoreInfo = SelfSignedCertificateGenerator.generateTemporarySelfSignedCertificate(getToolName(), CryptoHelper.KEY_STORE_TYPE_JKS);
sslUtil = new SSLUtil(new KeyStoreKeyManager(keyStoreInfo.getFirst(), keyStoreInfo.getSecond(), CryptoHelper.KEY_STORE_TYPE_JKS, null, true), new TrustAllTrustManager(false));
} else {
sslUtil = createSSLUtil(true);
}
config.setServerSocketFactory(sslUtil.createSSLServerSocketFactory());
} catch (final Exception e) {
err("Unable to create a server socket factory to accept SSL-based " + "client connections: ", StaticUtils.getExceptionMessage(e));
return ResultCode.LOCAL_ERROR;
}
}
listener = new LDAPListener(config);
try {
listener.startListening();
} catch (final Exception e) {
err("Unable to start listening for client connections: ", StaticUtils.getExceptionMessage(e));
return ResultCode.LOCAL_ERROR;
}
// Display a message with information about the port on which it is
// listening for connections.
int port = listener.getListenPort();
while (port <= 0) {
try {
Thread.sleep(1L);
} catch (final Exception e) {
Debug.debugException(e);
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
}
port = listener.getListenPort();
}
if (listenUsingSSL.isPresent()) {
out("Listening for SSL-based LDAP client connections on port ", port);
} else {
out("Listening for LDAP client connections on port ", port);
}
// Note that at this point, the listener will continue running in a
// separate thread, so we can return from this thread without exiting the
// program. However, we'll want to register a shutdown hook so that we can
// close the logger.
shutdownListener = new LDAPDebuggerShutdownListener(listener, logHandler);
Runtime.getRuntime().addShutdownHook(shutdownListener);
return ResultCode.SUCCESS;
}
use of com.unboundid.util.MinimalLogFormatter in project ldapsdk by pingidentity.
the class JSONAccessLogRequestHandlerTestCase method createListener.
/**
* Creates a new listener that will write log messages to an in-memory buffer.
*
* @throws Exception If an unexpected problem occurs.
*/
@BeforeClass()
public void createListener() throws Exception {
logHandler = new MemoryBasedLogHandler();
logHandler.setFormatter(new MinimalLogFormatter(null, false, false, false));
logHandler.setLevel(Level.INFO);
final CannedResponseRequestHandler successHandler = new CannedResponseRequestHandler();
final LDAPListenerConfig successConfig = new LDAPListenerConfig(0, new JSONAccessLogRequestHandler(logHandler, successHandler));
successListener = new LDAPListener(successConfig);
successListener.startListening();
successPort = successListener.getListenPort();
assertTrue(successPort > 0);
final CannedResponseRequestHandler failureHandler = new CannedResponseRequestHandler(ResultCode.NO_SUCH_OBJECT, "dc=example,dc=com", "The target entry was not found", Arrays.asList("ldap://server1.example.com/dc=example,dc=com", "ldap://server2.example.com/dc=example,dc=com"));
final LDAPListenerConfig failureConfig = new LDAPListenerConfig(0, new JSONAccessLogRequestHandler(logHandler, failureHandler));
failureListener = new LDAPListener(failureConfig);
failureListener.startListening();
failurePort = failureListener.getListenPort();
assertTrue(failurePort > 0);
}
use of com.unboundid.util.MinimalLogFormatter in project ldapsdk by pingidentity.
the class AccessLogRequestHandlerTestCase method createListener.
/**
* Creates a new listener that will write log messages to an in-memory buffer.
*
* @throws Exception If an unexpected problem occurs.
*/
@BeforeClass()
public void createListener() throws Exception {
logHandler = new MemoryBasedLogHandler();
logHandler.setFormatter(new MinimalLogFormatter());
logHandler.setLevel(Level.INFO);
final CannedResponseRequestHandler successHandler = new CannedResponseRequestHandler();
final LDAPListenerConfig successConfig = new LDAPListenerConfig(0, new AccessLogRequestHandler(logHandler, successHandler));
successListener = new LDAPListener(successConfig);
successListener.startListening();
successPort = successListener.getListenPort();
assertTrue(successPort > 0);
final CannedResponseRequestHandler failureHandler = new CannedResponseRequestHandler(ResultCode.NO_SUCH_OBJECT, "dc=example,dc=com", "The target entry was not found", Arrays.asList("ldap://server1.example.com/dc=example,dc=com", "ldap://server2.example.com/dc=example,dc=com"));
final LDAPListenerConfig failureConfig = new LDAPListenerConfig(0, new AccessLogRequestHandler(logHandler, failureHandler));
failureListener = new LDAPListener(failureConfig);
failureListener.startListening();
failurePort = failureListener.getListenPort();
assertTrue(failurePort > 0);
}
use of com.unboundid.util.MinimalLogFormatter in project ldapsdk by pingidentity.
the class InMemoryDirectoryServerTool method getConfig.
/**
* Creates a server configuration based on information provided with
* command line arguments.
*
* @return The configuration that was created.
*
* @throws LDAPException If a problem is encountered while creating the
* configuration.
*/
@NotNull()
private InMemoryDirectoryServerConfig getConfig() throws LDAPException {
final List<DN> dnList = baseDNArgument.getValues();
final DN[] baseDNs = new DN[dnList.size()];
dnList.toArray(baseDNs);
final InMemoryDirectoryServerConfig serverConfig = new InMemoryDirectoryServerConfig(baseDNs);
// If a listen port was specified, then update the configuration to use it.
int listenPort = 0;
if (portArgument.isPresent()) {
listenPort = portArgument.getValue();
}
// If schema should be used, then get it.
if (useDefaultSchemaArgument.isPresent()) {
serverConfig.setSchema(Schema.getDefaultStandardSchema());
} else if (useSchemaFileArgument.isPresent()) {
final Map<String, File> schemaFiles = new TreeMap<>();
for (final File f : useSchemaFileArgument.getValues()) {
if (f.exists()) {
if (f.isFile()) {
schemaFiles.put(f.getName(), f);
} else {
for (final File subFile : f.listFiles()) {
if (subFile.isFile()) {
schemaFiles.put(subFile.getName(), subFile);
}
}
}
} else {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_NO_SUCH_SCHEMA_FILE.get(f.getAbsolutePath()));
}
}
if (!doNotValidateSchemaDefinitionsArgument.isPresent()) {
Schema schema = null;
final List<String> errorMessages = new ArrayList<>();
final SchemaValidator schemaValidator = new SchemaValidator();
for (final File schemaFile : schemaFiles.values()) {
schema = schemaValidator.validateSchema(schemaFile, schema, errorMessages);
}
if (!errorMessages.isEmpty()) {
wrapErr(0, WRAP_COLUMN, WARN_MEM_DS_TOOL_SCHEMA_ISSUES_IDENTIFIED.get());
for (final String message : errorMessages) {
err();
final List<String> wrappedLines = StaticUtils.wrapLine(message, (WRAP_COLUMN - 2));
final Iterator<String> iterator = wrappedLines.iterator();
err("* " + iterator.next());
while (iterator.hasNext()) {
err(" " + iterator.next());
}
}
err();
wrapErr(0, WRAP_COLUMN, WARN_MEM_DS_TOOL_WILL_CONTINUE_WITH_SCHEMA.get(doNotValidateSchemaDefinitionsArgument.getIdentifierString()));
err();
}
}
try {
serverConfig.setSchema(Schema.getSchema(new ArrayList<File>(schemaFiles.values())));
} catch (final Exception e) {
Debug.debugException(e);
final StringBuilder fileList = new StringBuilder();
final Iterator<File> fileIterator = schemaFiles.values().iterator();
while (fileIterator.hasNext()) {
fileList.append(fileIterator.next().getAbsolutePath());
if (fileIterator.hasNext()) {
fileList.append(", ");
}
}
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_READING_SCHEMA.get(fileList, StaticUtils.getExceptionMessage(e)), e);
}
} else {
serverConfig.setSchema(null);
}
// the configuration.
if (additionalBindDNArgument.isPresent()) {
serverConfig.addAdditionalBindCredentials(additionalBindDNArgument.getValue().toString(), additionalBindPasswordArgument.getValue());
}
// configuration with that.
if (maxChangeLogEntriesArgument.isPresent()) {
serverConfig.setMaxChangeLogEntries(maxChangeLogEntriesArgument.getValue());
}
// the configuration with that.
if (maxConcurrentConnectionsArgument.isPresent()) {
serverConfig.setMaxConnections(maxConcurrentConnectionsArgument.getValue());
}
// If a size limit was specified, then update the configuration with that.
if (sizeLimitArgument.isPresent()) {
serverConfig.setMaxSizeLimit(sizeLimitArgument.getValue());
}
// If the password argument was specified, then set the password arguments.
if (passwordAttributeArgument.isPresent()) {
serverConfig.setPasswordAttributes(passwordAttributeArgument.getValues());
}
// Configure password encodings for the server.
final LinkedHashMap<String, InMemoryPasswordEncoder> passwordEncoders = new LinkedHashMap<>(10);
addUnsaltedEncoder("MD5", "MD5", passwordEncoders);
addUnsaltedEncoder("SHA", "SHA-1", passwordEncoders);
addUnsaltedEncoder("SHA1", "SHA-1", passwordEncoders);
addUnsaltedEncoder("SHA-1", "SHA-1", passwordEncoders);
addUnsaltedEncoder("SHA256", "SHA-256", passwordEncoders);
addUnsaltedEncoder("SHA-256", "SHA-256", passwordEncoders);
addUnsaltedEncoder("SHA384", "SHA-384", passwordEncoders);
addUnsaltedEncoder("SHA-384", "SHA-384", passwordEncoders);
addUnsaltedEncoder("SHA512", "SHA-512", passwordEncoders);
addUnsaltedEncoder("SHA-512", "SHA-512", passwordEncoders);
addSaltedEncoder("SMD5", "MD5", passwordEncoders);
addSaltedEncoder("SSHA", "SHA-1", passwordEncoders);
addSaltedEncoder("SSHA1", "SHA-1", passwordEncoders);
addSaltedEncoder("SSHA-1", "SHA-1", passwordEncoders);
addSaltedEncoder("SSHA256", "SHA-256", passwordEncoders);
addSaltedEncoder("SSHA-256", "SHA-256", passwordEncoders);
addSaltedEncoder("SSHA384", "SHA-384", passwordEncoders);
addSaltedEncoder("SSHA-384", "SHA-384", passwordEncoders);
addSaltedEncoder("SSHA512", "SHA-512", passwordEncoders);
addSaltedEncoder("SSHA-512", "SHA-512", passwordEncoders);
addClearEncoder("CLEAR", null, passwordEncoders);
addClearEncoder("BASE64", Base64PasswordEncoderOutputFormatter.getInstance(), passwordEncoders);
addClearEncoder("HEX", HexPasswordEncoderOutputFormatter.getLowercaseInstance(), passwordEncoders);
final InMemoryPasswordEncoder primaryEncoder;
if (defaultPasswordEncodingArgument.isPresent()) {
primaryEncoder = passwordEncoders.remove(StaticUtils.toLowerCase(defaultPasswordEncodingArgument.getValue()));
if (primaryEncoder == null) {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNAVAILABLE_PW_ENCODING.get(defaultPasswordEncodingArgument.getValue(), String.valueOf(passwordEncoders.keySet())));
}
} else {
primaryEncoder = null;
}
serverConfig.setPasswordEncoders(primaryEncoder, passwordEncoders.values());
// Configure the allowed operation types.
if (allowedOperationTypeArgument.isPresent()) {
final EnumSet<OperationType> operationTypes = EnumSet.noneOf(OperationType.class);
for (final String operationTypeName : allowedOperationTypeArgument.getValues()) {
final OperationType name = OperationType.forName(operationTypeName);
if (name == null) {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_ALLOWED_OP_TYPE.get(name));
} else {
switch(name) {
case ADD:
case BIND:
case COMPARE:
case DELETE:
case EXTENDED:
case MODIFY:
case MODIFY_DN:
case SEARCH:
operationTypes.add(name);
break;
case ABANDON:
case UNBIND:
default:
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_ALLOWED_OP_TYPE.get(name));
}
}
}
serverConfig.setAllowedOperationTypes(operationTypes);
}
// Configure the authentication required operation types.
if (authenticationRequiredOperationTypeArgument.isPresent()) {
final EnumSet<OperationType> operationTypes = EnumSet.noneOf(OperationType.class);
for (final String operationTypeName : authenticationRequiredOperationTypeArgument.getValues()) {
final OperationType name = OperationType.forName(operationTypeName);
if (name == null) {
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_AUTH_REQUIRED_OP_TYPE.get(name));
} else {
switch(name) {
case ADD:
case COMPARE:
case DELETE:
case EXTENDED:
case MODIFY:
case MODIFY_DN:
case SEARCH:
operationTypes.add(name);
break;
case ABANDON:
case UNBIND:
default:
throw new LDAPException(ResultCode.PARAM_ERROR, ERR_MEM_DS_TOOL_UNSUPPORTED_AUTH_REQUIRED_OP_TYPE.get(name));
}
}
}
serverConfig.setAuthenticationRequiredOperationTypes(operationTypes);
}
// handler.
if (accessLogToStandardOutArgument.isPresent()) {
final StreamHandler handler = new StreamHandler(System.out, new MinimalLogFormatter(null, false, false, true));
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
serverConfig.setAccessLogHandler(handler);
} else if (accessLogFileArgument.isPresent()) {
final File logFile = accessLogFileArgument.getValue();
try {
final FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
handler.setFormatter(new MinimalLogFormatter(null, false, false, true));
serverConfig.setAccessLogHandler(handler);
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_CREATING_LOG_HANDLER.get(logFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
}
}
// appropriate log handler.
if (jsonAccessLogToStandardOutArgument.isPresent()) {
final StreamHandler handler = new StreamHandler(System.out, new MinimalLogFormatter(null, false, false, true));
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
serverConfig.setJSONAccessLogHandler(handler);
} else if (jsonAccessLogFileArgument.isPresent()) {
final File logFile = jsonAccessLogFileArgument.getValue();
try {
final FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
handler.setFormatter(new MinimalLogFormatter(null, false, false, true));
serverConfig.setJSONAccessLogHandler(handler);
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_CREATING_LOG_HANDLER.get(logFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
}
}
// handler.
if (ldapDebugLogToStandardOutArgument.isPresent()) {
final StreamHandler handler = new StreamHandler(System.out, new MinimalLogFormatter(null, false, false, true));
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
serverConfig.setLDAPDebugLogHandler(handler);
} else if (ldapDebugLogFileArgument.isPresent()) {
final File logFile = ldapDebugLogFileArgument.getValue();
try {
final FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
StaticUtils.setLogHandlerLevel(handler, Level.INFO);
handler.setFormatter(new MinimalLogFormatter(null, false, false, true));
serverConfig.setLDAPDebugLogHandler(handler);
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_CREATING_LOG_HANDLER.get(logFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
}
}
// accordingly.
if (codeLogFile.isPresent()) {
serverConfig.setCodeLogDetails(codeLogFile.getValue().getAbsolutePath(), true);
}
// If SSL is to be used, then create the corresponding socket factories.
if (useSSLArgument.isPresent() || useStartTLSArgument.isPresent()) {
final File keyStorePath;
final char[] keyStorePIN;
final String keyStoreType;
if (keyStorePathArgument.isPresent()) {
keyStorePath = keyStorePathArgument.getValue();
keyStorePIN = keyStorePasswordArgument.getValue().toCharArray();
keyStoreType = keyStoreTypeArgument.getValue();
} else {
try {
keyStoreType = CryptoHelper.KEY_STORE_TYPE_JKS;
final ObjectPair<File, char[]> keyStoreInfo = SelfSignedCertificateGenerator.generateTemporarySelfSignedCertificate(getToolName(), keyStoreType);
keyStorePath = keyStoreInfo.getFirst();
keyStorePIN = keyStoreInfo.getSecond();
} catch (final CertException e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, e.getMessage(), e);
}
}
try {
final KeyManager keyManager = new KeyStoreKeyManager(keyStorePath, keyStorePIN, keyStoreType, null, true);
final TrustManager trustManager;
if (trustStorePathArgument.isPresent()) {
final char[] password;
if (trustStorePasswordArgument.isPresent()) {
password = trustStorePasswordArgument.getValue().toCharArray();
} else {
password = null;
}
trustManager = new TrustStoreTrustManager(trustStorePathArgument.getValue(), password, trustStoreTypeArgument.getValue(), true);
} else {
trustManager = new TrustAllTrustManager();
}
final SSLUtil serverSSLUtil = new SSLUtil(keyManager, trustManager);
final boolean requestCertificate;
final boolean requireCertificate;
final String clientAuthPolicy = sslClientAuthPolicy.getValue();
if (clientAuthPolicy.equalsIgnoreCase(SSL_CLIENT_AUTH_POLICY_OPTIONAL)) {
requestCertificate = true;
requireCertificate = false;
} else if (clientAuthPolicy.equalsIgnoreCase(SSL_CLIENT_AUTH_POLICY_REQUIRED)) {
requestCertificate = true;
requireCertificate = true;
} else {
requestCertificate = false;
requireCertificate = false;
}
if (useSSLArgument.isPresent()) {
final SSLUtil clientSSLUtil = new SSLUtil(new TrustAllTrustManager());
serverConfig.setListenerConfigs(InMemoryListenerConfig.createLDAPSConfig("LDAPS", null, listenPort, serverSSLUtil.createSSLServerSocketFactory(), clientSSLUtil.createSSLSocketFactory(), requestCertificate, requireCertificate));
} else {
serverConfig.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP+StartTLS", null, listenPort, serverSSLUtil.createSSLSocketFactory(), requestCertificate, requireCertificate));
}
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_MEM_DS_TOOL_ERROR_INITIALIZING_SSL.get(StaticUtils.getExceptionMessage(e)), e);
}
} else {
serverConfig.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", listenPort));
}
// them for use.
if (vendorNameArgument.isPresent()) {
serverConfig.setVendorName(vendorNameArgument.getValue());
}
if (vendorVersionArgument.isPresent()) {
serverConfig.setVendorVersion(vendorVersionArgument.getValue());
}
// If equality indexing is to be performed, then configure it.
if (equalityIndexArgument.isPresent()) {
serverConfig.setEqualityIndexAttributes(equalityIndexArgument.getValues());
}
// Update the configuration to indicate whether to generate operational
// attributes.
serverConfig.setGenerateOperationalAttributes(!doNotGenerateOperationalAttributesArgument.isPresent());
return serverConfig;
}
Aggregations