opendj-server-legacy/src/main/java/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java
@@ -26,12 +26,10 @@ */ package org.opends.server.admin.client.cli; import static com.forgerock.opendj.cli.ArgumentConstants.OPTION_LONG_ADMIN_UID; import static com.forgerock.opendj.cli.ArgumentConstants.*; import static com.forgerock.opendj.cli.CliMessages.*; import static com.forgerock.opendj.cli.ReturnCode.CONFLICTING_ARGS; import static com.forgerock.opendj.cli.ReturnCode.SUCCESS; import static com.forgerock.opendj.cli.Utils.LINE_SEPARATOR; import static org.forgerock.util.Utils.closeSilently; import static com.forgerock.opendj.cli.ReturnCode.*; import static com.forgerock.opendj.cli.Utils.*; import java.io.File; import java.io.FileInputStream; @@ -43,10 +41,13 @@ import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.forgerock.i18n.LocalizableMessage; import org.forgerock.i18n.LocalizableMessageBuilder; import org.forgerock.i18n.slf4j.LocalizedLogger; import org.forgerock.opendj.config.server.ConfigException; import org.opends.admin.ads.util.ApplicationTrustManager; import org.opends.server.admin.AdministrationConnector; import org.opends.server.admin.server.ServerManagementContext; @@ -54,7 +55,6 @@ import org.opends.server.admin.std.server.FileBasedTrustManagerProviderCfg; import org.opends.server.admin.std.server.RootCfg; import org.opends.server.admin.std.server.TrustManagerProviderCfg; import org.forgerock.opendj.config.server.ConfigException; import org.opends.server.core.DirectoryServer; import com.forgerock.opendj.cli.Argument; @@ -74,106 +74,69 @@ */ public final class SecureConnectionCliArgs { /** * The 'hostName' global argument. */ private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass(); /** The 'hostName' global argument. */ public StringArgument hostNameArg; /** * The 'port' global argument. */ /** The 'port' global argument. */ public IntegerArgument portArg; /** * The 'bindDN' global argument. */ /** The 'bindDN' global argument. */ public StringArgument bindDnArg; /** * The 'adminUID' global argument. */ /** The 'adminUID' global argument. */ public StringArgument adminUidArg; /** * The 'bindPasswordFile' global argument. */ /** The 'bindPasswordFile' global argument. */ public FileBasedArgument bindPasswordFileArg; /** * The 'bindPassword' global argument. */ /** The 'bindPassword' global argument. */ public StringArgument bindPasswordArg; /** * The 'trustAllArg' global argument. */ /** The 'trustAllArg' global argument. */ public BooleanArgument trustAllArg; /** * The 'trustStore' global argument. */ /** The 'trustStore' global argument. */ public StringArgument trustStorePathArg; /** * The 'trustStorePassword' global argument. */ /** The 'trustStorePassword' global argument. */ public StringArgument trustStorePasswordArg; /** * The 'trustStorePasswordFile' global argument. */ /** The 'trustStorePasswordFile' global argument. */ public FileBasedArgument trustStorePasswordFileArg; /** * The 'keyStore' global argument. */ /** The 'keyStore' global argument. */ public StringArgument keyStorePathArg; /** * The 'keyStorePassword' global argument. */ /** The 'keyStorePassword' global argument. */ public StringArgument keyStorePasswordArg; /** * The 'keyStorePasswordFile' global argument. */ /** The 'keyStorePasswordFile' global argument. */ public FileBasedArgument keyStorePasswordFileArg; /** * The 'certNicknameArg' global argument. */ /** The 'certNicknameArg' global argument. */ public StringArgument certNicknameArg; /** * The 'useSSLArg' global argument. */ /** The 'useSSLArg' global argument. */ public BooleanArgument useSSLArg; /** * The 'useStartTLSArg' global argument. */ /** The 'useStartTLSArg' global argument. */ public BooleanArgument useStartTLSArg; /** * Argument indicating a SASL option. */ public StringArgument saslOptionArg; /** Argument indicating a SASL option. */ public StringArgument saslOptionArg; /** * Argument to specify the connection timeout. */ /** Argument to specify the connection timeout. */ public IntegerArgument connectTimeoutArg; /** * Private container for global arguments. */ private LinkedHashSet<Argument> argList; /** Private container for global arguments. */ private Set<Argument> argList; /** The trust manager. */ private ApplicationTrustManager trustManager; private boolean configurationInitialized; private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass(); /** Defines if the CLI always use the SSL connection type. */ private boolean alwaysSSL; @@ -181,33 +144,34 @@ /** * Creates a new instance of secure arguments. * * @param alwaysSSL If true, always use the SSL connection type. In this case, * the arguments useSSL and startTLS are not present. * @param alwaysSSL * If true, always use the SSL connection type. In this case, the * arguments useSSL and startTLS are not present. */ public SecureConnectionCliArgs(boolean alwaysSSL) { if (alwaysSSL) { this.alwaysSSL = true; } this.alwaysSSL = alwaysSSL; } /** * Indicates whether or not any of the arguments are present. * * @return boolean where true indicates that at least one of the * arguments is present * @return boolean where true indicates that at least one of the arguments is * present */ public boolean argumentsPresent() { boolean present = false; if (argList != null) { for (Argument arg : argList) { if (arg.isPresent()) { present = true; break; public boolean argumentsPresent() { if (argList != null) { for (Argument arg : argList) { if (arg.isPresent()) { return true; } } } return present; return false; } /** @@ -240,8 +204,8 @@ /** * Get the bindDN which has to be used for the command. * * @return The bindDN specified by the command line argument, or the * default value, if not specified. * @return The bindDN specified by the command line argument, or the default * value, if not specified. */ public String getBindDN() { @@ -256,54 +220,55 @@ * Initialize Global option. * * @throws ArgumentException * If there is a problem with any of the parameters used * to create this argument. * If there is a problem with any of the parameters used to create * this argument. * @return a ArrayList with the options created. */ public LinkedHashSet<Argument> createGlobalArguments() throws ArgumentException public Set<Argument> createGlobalArguments() throws ArgumentException { argList = new LinkedHashSet<Argument>(); argList = new LinkedHashSet<>(); useSSLArg = CommonArguments.getUseSSL(); if (!alwaysSSL) { if (!alwaysSSL) { argList.add(useSSLArg); } else { } else { // simulate that the useSSL arg has been given in the CLI useSSLArg.setPresent(true); } useStartTLSArg = CommonArguments.getStartTLS(); if (!alwaysSSL) { if (!alwaysSSL) { argList.add(useStartTLSArg); } String defaultHostName; try { try { defaultHostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { defaultHostName="Unknown (" + e + ")"; } catch (Exception e) { defaultHostName = "Unknown (" + e + ")"; } hostNameArg = CommonArguments.getHostName(defaultHostName); argList.add(hostNameArg); portArg = CommonArguments.getPort( AdministrationConnector.DEFAULT_ADMINISTRATION_CONNECTOR_PORT, alwaysSSL ? INFO_DESCRIPTION_ADMIN_PORT.get() : INFO_DESCRIPTION_PORT.get()); portArg = CommonArguments.getPort(AdministrationConnector.DEFAULT_ADMINISTRATION_CONNECTOR_PORT, alwaysSSL ? INFO_DESCRIPTION_ADMIN_PORT.get() : INFO_DESCRIPTION_PORT.get()); argList.add(portArg); bindDnArg = CommonArguments.getBindDN("cn=Directory Manager"); bindDnArg = CommonArguments.getBindDN(CliConstants.DEFAULT_ROOT_USER_DN); argList.add(bindDnArg); // It is up to the classes that required admin UID to make this argument // visible and add it. adminUidArg = new StringArgument("adminUID", 'I', OPTION_LONG_ADMIN_UID, false, false, true, INFO_ADMINUID_PLACEHOLDER.get(), CliConstants.GLOBAL_ADMIN_UID, null, INFO_DESCRIPTION_ADMIN_UID.get()); adminUidArg = new StringArgument("adminUID", 'I', OPTION_LONG_ADMIN_UID, false, false, true, INFO_ADMINUID_PLACEHOLDER.get(), CliConstants.GLOBAL_ADMIN_UID, null, INFO_DESCRIPTION_ADMIN_UID.get()); adminUidArg.setPropertyName(OPTION_LONG_ADMIN_UID); adminUidArg.setHidden(true); @@ -350,8 +315,8 @@ /** * Get the host name which has to be used for the command. * * @return The host name specified by the command line argument, or * the default value, if not specified. * @return The host name specified by the command line argument, or the * default value, if not specified. */ public String getHostName() { @@ -380,85 +345,55 @@ /** * Indication if provided global options are validate. * * @param buf the LocalizableMessageBuilder to write the error messages. * @param buf * the LocalizableMessageBuilder to write the error messages. * @return return code. */ public int validateGlobalOptions(LocalizableMessageBuilder buf) { ArrayList<LocalizableMessage> errors = new ArrayList<LocalizableMessage>(); List<LocalizableMessage> errors = new ArrayList<>(); // Couldn't have at the same time bindPassword and bindPasswordFile if (bindPasswordArg.isPresent() && bindPasswordFileArg.isPresent()) { LocalizableMessage message = ERR_TOOL_CONFLICTING_ARGS.get( bindPasswordArg.getLongIdentifier(), bindPasswordFileArg.getLongIdentifier()); errors.add(message); if (bindPasswordArg.isPresent() && bindPasswordFileArg.isPresent()) { errors.add( ERR_TOOL_CONFLICTING_ARGS.get(bindPasswordArg.getLongIdentifier(), bindPasswordFileArg.getLongIdentifier())); } // Couldn't have at the same time trustAll and // trustStore related arg if (trustAllArg.isPresent() && trustStorePathArg.isPresent()) { LocalizableMessage message = ERR_TOOL_CONFLICTING_ARGS.get( trustAllArg.getLongIdentifier(), trustStorePathArg.getLongIdentifier()); errors.add(message); // Couldn't have at the same time trustAll and trustStore related arg if (trustAllArg.isPresent() && trustStorePathArg.isPresent()) { errors.add( ERR_TOOL_CONFLICTING_ARGS.get(trustAllArg.getLongIdentifier(), trustStorePathArg.getLongIdentifier())); } if (trustAllArg.isPresent() && trustStorePasswordArg.isPresent()) { LocalizableMessage message = ERR_TOOL_CONFLICTING_ARGS.get( trustAllArg.getLongIdentifier(), trustStorePasswordArg.getLongIdentifier()); errors.add(message); if (trustAllArg.isPresent() && trustStorePasswordArg.isPresent()) { errors.add( ERR_TOOL_CONFLICTING_ARGS.get(trustAllArg.getLongIdentifier(), trustStorePasswordArg.getLongIdentifier())); } if (trustAllArg.isPresent() && trustStorePasswordFileArg.isPresent()) { LocalizableMessage message = ERR_TOOL_CONFLICTING_ARGS.get( trustAllArg.getLongIdentifier(), trustStorePasswordFileArg.getLongIdentifier()); errors.add(message); if (trustAllArg.isPresent() && trustStorePasswordFileArg.isPresent()) { errors.add( ERR_TOOL_CONFLICTING_ARGS.get(trustAllArg.getLongIdentifier(), trustStorePasswordFileArg.getLongIdentifier())); } // Couldn't have at the same time trustStorePasswordArg and // trustStorePasswordFileArg if (trustStorePasswordArg.isPresent() && trustStorePasswordFileArg.isPresent()) { if (trustStorePasswordArg.isPresent() && trustStorePasswordFileArg.isPresent()) { LocalizableMessage message = ERR_TOOL_CONFLICTING_ARGS.get( trustStorePasswordArg.getLongIdentifier(), trustStorePasswordFileArg.getLongIdentifier()); trustStorePasswordArg.getLongIdentifier(), trustStorePasswordFileArg.getLongIdentifier()); errors.add(message); } if (trustStorePathArg.isPresent()) checkIfPathArgumentIsReadable( trustStorePathArg, errors, ERR_CANNOT_READ_TRUSTSTORE.get(trustStorePathArg.getValue())); checkIfPathArgumentIsReadable( keyStorePathArg, errors, ERR_CANNOT_READ_KEYSTORE.get(keyStorePasswordArg.getValue())); // Couldn't have at the same time startTLSArg and useSSLArg if (useStartTLSArg.isPresent() && useSSLArg.isPresent()) { // Check that the path exists and is readable String value = trustStorePathArg.getValue(); if (!canRead(trustStorePathArg.getValue())) { LocalizableMessage message = ERR_CANNOT_READ_TRUSTSTORE.get( value); errors.add(message); } errors.add(ERR_TOOL_CONFLICTING_ARGS.get(useStartTLSArg.getLongIdentifier(), useSSLArg.getLongIdentifier())); } if (keyStorePathArg.isPresent()) { // Check that the path exists and is readable String value = keyStorePathArg.getValue(); if (!canRead(trustStorePathArg.getValue())) { LocalizableMessage message = ERR_CANNOT_READ_KEYSTORE.get( value); errors.add(message); } } // Couldn't have at the same time startTLSArg and // useSSLArg if (useStartTLSArg.isPresent() && useSSLArg.isPresent()) { LocalizableMessage message = ERR_TOOL_CONFLICTING_ARGS.get( useStartTLSArg .getLongIdentifier(), useSSLArg.getLongIdentifier()); errors.add(message); } if (errors.size() > 0) if (!errors.isEmpty()) { for (LocalizableMessage error : errors) { @@ -474,6 +409,15 @@ return SUCCESS.get(); } private void checkIfPathArgumentIsReadable( StringArgument pathArgument, List<LocalizableMessage> errors, LocalizableMessage errorMessage) { if (pathArgument.isPresent() && !canRead(pathArgument.getValue())) { errors.add(errorMessage); } } /** * Indicate if the SSL mode is required. * @@ -513,76 +457,62 @@ { if (trustManager == null) { KeyStore truststore = null ; KeyStore truststore = null; if (trustAllArg.isPresent()) { // Running a null TrustManager will force createLdapsContext and // createStartTLSContext to use a bindTrustManager. return null ; return null; } else if (trustStorePathArg.isPresent()) else if (trustStorePathArg.isPresent()) { try (final FileInputStream fos = new FileInputStream(trustStorePathArg.getValue())) { FileInputStream fos = null; try String trustStorePasswordStringValue = null; if (trustStorePasswordArg.isPresent()) { fos = new FileInputStream(trustStorePathArg.getValue()); String trustStorePasswordStringValue = null; char[] trustStorePasswordValue = null; if (trustStorePasswordArg.isPresent()) { trustStorePasswordStringValue = trustStorePasswordArg.getValue(); } else if (trustStorePasswordFileArg.isPresent()) { trustStorePasswordStringValue = trustStorePasswordFileArg.getValue(); } if (trustStorePasswordStringValue != null) { trustStorePasswordStringValue = System .getProperty("javax.net.ssl.trustStorePassword"); } if (trustStorePasswordStringValue != null) { trustStorePasswordValue = trustStorePasswordStringValue.toCharArray(); } truststore = KeyStore.getInstance(KeyStore.getDefaultType()); truststore.load(fos, trustStorePasswordValue); trustStorePasswordStringValue = trustStorePasswordArg.getValue(); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) else if (trustStorePasswordFileArg.isPresent()) { // Nothing to do: if this occurs we will systematically refuse the // certificates. Maybe we should avoid this and be strict, but we // are in a best effort mode. logger.warn(LocalizableMessage.raw("Error with the truststore"), e); trustStorePasswordStringValue = trustStorePasswordFileArg.getValue(); } finally if (trustStorePasswordStringValue != null) { closeSilently(fos); trustStorePasswordStringValue = System.getProperty("javax.net.ssl.trustStorePassword"); } char[] trustStorePasswordValue = null; if (trustStorePasswordStringValue != null) { trustStorePasswordValue = trustStorePasswordStringValue.toCharArray(); } truststore = KeyStore.getInstance(KeyStore.getDefaultType()); truststore.load(fos, trustStorePasswordValue); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { // Nothing to do: if this occurs we will systematically refuse the // certificates. Maybe we should avoid this and be strict, but we // are in a best effort mode. logger.warn(LocalizableMessage.raw("Error with the truststore"), e); } } trustManager = new ApplicationTrustManager(truststore); } return trustManager; } /** * Returns {@code true} if we can read on the provided path and * {@code false} otherwise. * Returns {@code true} if we can read on the provided path and {@code false} * otherwise. * * @param path * the path. * @return {@code true} if we can read on the provided path and * {@code false} otherwise. * @return {@code true} if we can read on the provided path and {@code false} * otherwise. */ private boolean canRead(String path) { @@ -592,8 +522,8 @@ /** * Returns the absolute path of the trust store file that appears on the * config. Returns {@code null} if the trust store is not defined or it * does not exist. * config. Returns {@code null} if the trust store is not defined or it does * not exist. * * @return the absolute path of the trust store file that appears on the * config. @@ -608,29 +538,30 @@ boolean couldInitializeConfig = configurationInitialized; // Initialization for admin framework if (!configurationInitialized) { if (!configurationInitialized) { couldInitializeConfig = initializeConfiguration(); } if (couldInitializeConfig) { // Get the Directory Server configuration handler and use it. RootCfg root = ServerManagementContext.getInstance().getRootConfiguration(); RootCfg root = ServerManagementContext.getInstance().getRootConfiguration(); administrationConnectorCfg = root.getAdministrationConnector(); String trustManagerStr = administrationConnectorCfg.getTrustManagerProvider(); String trustManagerStr = administrationConnectorCfg.getTrustManagerProvider(); trustManagerCfg = root.getTrustManagerProvider(trustManagerStr); if (trustManagerCfg instanceof FileBasedTrustManagerProviderCfg) { FileBasedTrustManagerProviderCfg fileBasedTrustManagerCfg = (FileBasedTrustManagerProviderCfg) trustManagerCfg; if (trustManagerCfg instanceof FileBasedTrustManagerProviderCfg) { FileBasedTrustManagerProviderCfg fileBasedTrustManagerCfg = (FileBasedTrustManagerProviderCfg) trustManagerCfg; String truststoreFile = fileBasedTrustManagerCfg.getTrustStoreFile(); // Check the file if (truststoreFile.startsWith(File.separator)) { if (truststoreFile.startsWith(File.separator)) { truststoreFileAbsolute = truststoreFile; } else { truststoreFileAbsolute = DirectoryServer.getInstanceRoot() + File.separator + truststoreFile; } else { truststoreFileAbsolute = DirectoryServer.getInstanceRoot() + File.separator + truststoreFile; } File f = new File(truststoreFileAbsolute); if (!f.exists() || !f.canRead() || f.isDirectory()) @@ -663,36 +594,40 @@ */ public int getAdminPortFromConfig() throws ConfigException { int port; // Initialization for admin framework boolean couldInitializeConfiguration = configurationInitialized; if (!configurationInitialized) { if (!configurationInitialized) { couldInitializeConfiguration = initializeConfiguration(); } if (couldInitializeConfiguration) { RootCfg root = ServerManagementContext.getInstance().getRootConfiguration(); port = root.getAdministrationConnector().getListenPort(); RootCfg root = ServerManagementContext.getInstance().getRootConfiguration(); return root.getAdministrationConnector().getListenPort(); } else { port = AdministrationConnector.DEFAULT_ADMINISTRATION_CONNECTOR_PORT; return AdministrationConnector.DEFAULT_ADMINISTRATION_CONNECTOR_PORT; } return port; } private boolean initializeConfiguration() { private boolean initializeConfiguration() { // check if the initialization is required try { ServerManagementContext.getInstance().getRootConfiguration(). getAdministrationConnector(); } catch (java.lang.Throwable th) { try { try { ServerManagementContext.getInstance().getRootConfiguration().getAdministrationConnector(); } catch (java.lang.Throwable th) { try { DirectoryServer.bootstrapClient(); DirectoryServer.initializeJMX(); DirectoryServer.getInstance().initializeConfiguration(); } catch (Exception ex) { } catch (Exception ex) { // do nothing return false; } @@ -712,17 +647,21 @@ public int getPortFromConfig() { int portNumber; if (alwaysSSL()) { portNumber = AdministrationConnector.DEFAULT_ADMINISTRATION_CONNECTOR_PORT; if (alwaysSSL()) { portNumber = AdministrationConnector.DEFAULT_ADMINISTRATION_CONNECTOR_PORT; // Try to get the port from the config file try { portNumber = getAdminPortFromConfig(); } catch (ConfigException ex) { } catch (ConfigException ex) { // Nothing to do } } else { } else { portNumber = CliConstants.DEFAULT_SSL_PORT; } return portNumber; @@ -737,8 +676,7 @@ */ public void initArgumentsWithConfiguration() throws ConfigException { int portNumber = getPortFromConfig(); portArg.setDefaultValue(String.valueOf(portNumber)); portArg.setDefaultValue(String.valueOf(getPortFromConfig())); String truststoreFileAbsolute = getTruststoreFileFromConfig(); if (truststoreFileAbsolute != null) opendj-server-legacy/src/main/java/org/opends/server/admin/client/cli/SecureConnectionCliParser.java
@@ -28,16 +28,14 @@ package org.opends.server.admin.client.cli; import static com.forgerock.opendj.cli.CliMessages.*; import static com.forgerock.opendj.cli.Utils.LINE_SEPARATOR; import static com.forgerock.opendj.cli.Utils.MAX_LINE_WIDTH; import static com.forgerock.opendj.cli.Utils.wrapText; import static com.forgerock.opendj.cli.ReturnCode.CONFLICTING_ARGS; import static com.forgerock.opendj.cli.ReturnCode.*; import static com.forgerock.opendj.cli.Utils.*; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.forgerock.i18n.LocalizableMessage; import org.forgerock.i18n.LocalizableMessageBuilder; @@ -241,12 +239,10 @@ * to create this argument. * @return a ArrayList with the options created. */ protected LinkedHashSet<Argument> createGlobalArguments( OutputStream outStream, boolean alwaysSSL) throws ArgumentException protected Set<Argument> createGlobalArguments(OutputStream outStream, boolean alwaysSSL) throws ArgumentException { secureArgsList = new SecureConnectionCliArgs(alwaysSSL); LinkedHashSet<Argument> set = secureArgsList.createGlobalArguments(); Set<Argument> set = secureArgsList.createGlobalArguments(); showUsageArg = CommonArguments.getShowUsage(); setUsageArgument(showUsageArg, outStream); opendj-server-legacy/src/main/java/org/opends/server/util/BuildVersion.java
@@ -22,22 +22,20 @@ * * * Copyright 2008 Sun Microsystems, Inc. * Portions copyright 2013-2014 ForgeRock AS. * Portions copyright 2013-2015 ForgeRock AS. */ package org.opends.server.util; import static org.opends.messages.ToolMessages.ERR_BUILDVERSION_NOT_FOUND; import static org.opends.messages.ToolMessages.ERR_BUILDVERSION_MALFORMED; import static org.opends.messages.ToolMessages.ERR_BUILDVERSION_MISMATCH; import static org.opends.server.config.ConfigConstants.CONFIG_DIR_NAME; import static org.forgerock.util.Utils.closeSilently; import static org.opends.messages.ToolMessages.*; import static org.opends.server.config.ConfigConstants.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; import java.util.Arrays; import org.forgerock.util.Utils; import org.opends.server.core.DirectoryServer; import org.opends.server.types.InitializationException; @@ -78,37 +76,23 @@ */ public static BuildVersion instanceVersion() throws InitializationException { final String buildInfo = DirectoryServer.getInstanceRoot() + File.separator + CONFIG_DIR_NAME + File.separator + "buildinfo"; BufferedReader reader = null; try final String buildInfo = Paths.get(DirectoryServer.getInstanceRoot(), CONFIG_DIR_NAME, "buildinfo").toString(); try (final BufferedReader reader = new BufferedReader(new FileReader(buildInfo))) { reader = new BufferedReader(new FileReader(buildInfo)); final String s = reader.readLine(); if (s != null) if (s == null) { return valueOf(s); throw new InitializationException(ERR_BUILDVERSION_MALFORMED.get(buildInfo)); } else { throw new InitializationException(ERR_BUILDVERSION_MALFORMED .get(buildInfo)); } return valueOf(s); } catch (IOException e) { throw new InitializationException(ERR_BUILDVERSION_NOT_FOUND .get(buildInfo)); throw new InitializationException(ERR_BUILDVERSION_NOT_FOUND.get(buildInfo)); } catch (final IllegalArgumentException e) { throw new InitializationException(ERR_BUILDVERSION_MALFORMED .get(buildInfo)); } finally { closeSilently(reader); throw new InitializationException(ERR_BUILDVERSION_MALFORMED.get(buildInfo)); } } @@ -120,11 +104,10 @@ */ public static void checkVersionMismatch() throws InitializationException { if (!BuildVersion.binaryVersion().toString().equals( BuildVersion.instanceVersion().toString())) if (!BuildVersion.binaryVersion().toString().equals(BuildVersion.instanceVersion().toString())) { throw new InitializationException(ERR_BUILDVERSION_MISMATCH.get( BuildVersion.binaryVersion(), BuildVersion.instanceVersion())); throw new InitializationException( ERR_BUILDVERSION_MISMATCH.get(BuildVersion.binaryVersion(), BuildVersion.instanceVersion())); } } @@ -142,8 +125,7 @@ * @throws IllegalArgumentException * If the string does not contain a parsable build version. */ public static BuildVersion valueOf(final String s) throws IllegalArgumentException public static BuildVersion valueOf(final String s) throws IllegalArgumentException { final String[] fields = s.split("\\."); if (fields.length != 4) @@ -169,8 +151,7 @@ * @param rev * VCS revision number. */ public BuildVersion(final int major, final int minor, final int point, final long rev) public BuildVersion(final int major, final int minor, final int point, final long rev) { this.major = major; this.minor = minor; @@ -178,7 +159,7 @@ this.rev = rev; } /** {@inheritDoc} */ @Override public int compareTo(final BuildVersion version) { if (major == version.major) @@ -213,7 +194,7 @@ return 1; } /** {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) @@ -223,8 +204,7 @@ else if (obj instanceof BuildVersion) { final BuildVersion other = (BuildVersion) obj; return major == other.major && minor == other.minor && point == other.point && rev == other.rev; return major == other.major && minor == other.minor && point == other.point && rev == other.rev; } else { @@ -272,25 +252,15 @@ return rev; } /** {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(new int[] { major, minor, point, (int) (rev >>> 32), (int) (rev & 0xFFFFL) }); return Arrays.hashCode(new int[] { major, minor, point, (int) (rev >>> 32), (int) (rev & 0xFFFFL) }); } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(major); builder.append('.'); builder.append(minor); builder.append('.'); builder.append(point); builder.append('.'); builder.append(rev); return builder.toString(); return Utils.joinAsString(".", major, minor, point, rev); } } opendj-server-legacy/src/main/java/org/opends/server/util/args/LDAPConnectionArgumentParser.java
@@ -26,13 +26,13 @@ */ package org.opends.server.util.args; import static com.forgerock.opendj.cli.Utils.*; import static org.opends.messages.ToolMessages.*; import static com.forgerock.opendj.cli.Utils.*; import java.io.PrintStream; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLException; @@ -61,123 +61,116 @@ * Creates an argument parser pre-populated with arguments for specifying * information for opening and LDAPConnection an LDAP connection. */ public class LDAPConnectionArgumentParser extends ArgumentParser { public class LDAPConnectionArgumentParser extends ArgumentParser { private SecureConnectionCliArgs args; /** * Creates a new instance of this argument parser with no arguments. * Unnamed trailing arguments will not be allowed. * Creates a new instance of this argument parser with no arguments. Unnamed * trailing arguments will not be allowed. * * @param mainClassName The fully-qualified name of the Java * class that should be invoked to launch * the program with which this argument * parser is associated. * @param toolDescription A human-readable description for the * tool, which will be included when * displaying usage information. * @param longArgumentsCaseSensitive Indicates whether long arguments should * @param argumentGroup Group to which LDAP arguments will be * added to the parser. May be null to * indicate that arguments should be * added to the default group * @param alwaysSSL If true, always use the SSL connection type. In this case, * the arguments useSSL and startTLS are not present. */ public LDAPConnectionArgumentParser(String mainClassName, LocalizableMessage toolDescription, boolean longArgumentsCaseSensitive, ArgumentGroup argumentGroup, boolean alwaysSSL) { * @param mainClassName * The fully-qualified name of the Java class that should be invoked * to launch the program with which this argument parser is * associated. * @param toolDescription * A human-readable description for the tool, which will be included * when displaying usage information. * @param longArgumentsCaseSensitive * Indicates whether long arguments should * @param argumentGroup * Group to which LDAP arguments will be added to the parser. May be * null to indicate that arguments should be added to the default * group * @param alwaysSSL * If true, always use the SSL connection type. In this case, the * arguments useSSL and startTLS are not present. */ public LDAPConnectionArgumentParser(String mainClassName, LocalizableMessage toolDescription, boolean longArgumentsCaseSensitive, ArgumentGroup argumentGroup, boolean alwaysSSL) { super(mainClassName, toolDescription, longArgumentsCaseSensitive); addLdapConnectionArguments(argumentGroup, alwaysSSL); setVersionHandler(new DirectoryServerVersionHandler()); } /** * Indicates whether or not the user has indicated that they would like * to perform a remote operation based on the arguments. * Indicates whether or not the user has indicated that they would like to * perform a remote operation based on the arguments. * * @return true if the user wants to perform a remote operation; * false otherwise * @return true if the user wants to perform a remote operation; false * otherwise */ public boolean connectionArgumentsPresent() { public boolean connectionArgumentsPresent() { return args != null && args.argumentsPresent(); } /** * Creates a new LDAPConnection and invokes a connect operation using * information provided in the parsed set of arguments that were provided * by the user. * information provided in the parsed set of arguments that were provided by * the user. * * @param out stream to write messages * @param err stream to write error messages * @param out * stream to write messages * @param err * stream to write error messages * @return LDAPConnection created by this class from parsed arguments * @throws LDAPConnectionException if there was a problem connecting * to the server indicated by the input arguments * @throws ArgumentException if there was a problem processing the input * arguments * @throws LDAPConnectionException * if there was a problem connecting to the server indicated by the * input arguments * @throws ArgumentException * if there was a problem processing the input arguments */ public LDAPConnection connect(PrintStream out, PrintStream err) throws LDAPConnectionException, ArgumentException public LDAPConnection connect(PrintStream out, PrintStream err) throws LDAPConnectionException, ArgumentException { return connect(this.args, out, err); } /** * Creates a new LDAPConnection and invokes a connect operation using * information provided in the parsed set of arguments that were provided * by the user. * information provided in the parsed set of arguments that were provided by * the user. * * @param args with which to connect * @param out stream to write messages * @param err stream to write error messages * @param args * with which to connect * @param out * stream to write messages * @param err * stream to write error messages * @return LDAPConnection created by this class from parsed arguments * @throws LDAPConnectionException if there was a problem connecting * to the server indicated by the input arguments * @throws ArgumentException if there was a problem processing the input * arguments * @throws LDAPConnectionException * if there was a problem connecting to the server indicated by the * input arguments * @throws ArgumentException * if there was a problem processing the input arguments */ private LDAPConnection connect(SecureConnectionCliArgs args, PrintStream out, PrintStream err) throws LDAPConnectionException, ArgumentException private LDAPConnection connect(SecureConnectionCliArgs args, PrintStream out, PrintStream err) throws LDAPConnectionException, ArgumentException { // If both a bind password and bind password file were provided, then return // an error. if (args.bindPasswordArg.isPresent() && args.bindPasswordFileArg.isPresent()) if (args.bindPasswordArg.isPresent() && args.bindPasswordFileArg.isPresent()) { LocalizableMessage message = ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.bindPasswordArg.getLongIdentifier(), args.bindPasswordFileArg.getLongIdentifier()); err.println(wrapText(message, MAX_LINE_WIDTH)); throw new ArgumentException(message); printAndThrowException(err, ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.bindPasswordArg.getLongIdentifier(), args.bindPasswordFileArg.getLongIdentifier())); } // If both a key store password and key store password file were provided, // then return an error. if (args.keyStorePasswordArg.isPresent() && args.keyStorePasswordFileArg.isPresent()) if (args.keyStorePasswordArg.isPresent() && args.keyStorePasswordFileArg.isPresent()) { LocalizableMessage message = ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.keyStorePasswordArg.getLongIdentifier(), args.keyStorePasswordFileArg.getLongIdentifier()); throw new ArgumentException(message); printAndThrowException(err, ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.keyStorePasswordArg.getLongIdentifier(), args.keyStorePasswordFileArg.getLongIdentifier())); } // If both a trust store password and trust store password file were // provided, then return an error. if (args.trustStorePasswordArg.isPresent() && args.trustStorePasswordFileArg.isPresent()) if (args.trustStorePasswordArg.isPresent() && args.trustStorePasswordFileArg.isPresent()) { LocalizableMessage message = ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.trustStorePasswordArg.getLongIdentifier(), args.trustStorePasswordFileArg.getLongIdentifier()); err.println(wrapText(message, MAX_LINE_WIDTH)); throw new ArgumentException(message); printAndThrowException(err, ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.trustStorePasswordArg.getLongIdentifier(), args.trustStorePasswordFileArg.getLongIdentifier())); } // Create the LDAP connection options object, which will be used to @@ -186,18 +179,14 @@ LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions(); connectionOptions.setVersionNumber(3); // See if we should use SSL or StartTLS when establishing the connection. // If so, then make sure only one of them was specified. if (args.useSSLArg.isPresent()) { if (args.useStartTLSArg.isPresent()) { LocalizableMessage message = ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.useSSLArg.getLongIdentifier(), args.useSSLArg.getLongIdentifier()); err.println(wrapText(message, MAX_LINE_WIDTH)); throw new ArgumentException(message); printAndThrowException(err, ERR_LDAP_CONN_MUTUALLY_EXCLUSIVE_ARGUMENTS.get( args.useSSLArg.getLongIdentifier(), args.useSSLArg.getLongIdentifier())); } connectionOptions.setUseSSL(true); } @@ -206,7 +195,6 @@ connectionOptions.setStartTLS(true); } // If we should blindly trust any certificate, then install the appropriate // SSL connection factory. if (args.useSSLArg.isPresent() || args.useStartTLSArg.isPresent()) @@ -225,44 +213,37 @@ SSLConnectionFactory sslConnectionFactory = new SSLConnectionFactory(); sslConnectionFactory.init(args.trustAllArg.isPresent(), args.keyStorePathArg.getValue(), args.keyStorePasswordArg.getValue(), clientAlias, args.trustStorePathArg.getValue(), args.trustStorePasswordArg.getValue()); args.keyStorePathArg.getValue(), args.keyStorePasswordArg.getValue(), clientAlias, args.trustStorePathArg.getValue(), args.trustStorePasswordArg.getValue()); connectionOptions.setSSLConnectionFactory(sslConnectionFactory); } catch (SSLConnectionException sce) { LocalizableMessage message = ERR_LDAP_CONN_CANNOT_INITIALIZE_SSL.get(sce.getMessage()); err.println(wrapText(message, MAX_LINE_WIDTH)); err.println(wrapText(ERR_LDAP_CONN_CANNOT_INITIALIZE_SSL.get(sce.getMessage()), MAX_LINE_WIDTH)); } } // If one or more SASL options were provided, then make sure that one of // them was "mech" and specified a valid SASL mechanism. if (args.saslOptionArg.isPresent()) { String mechanism = null; LinkedList<String> options = new LinkedList<String>(); String mechanism = null; LinkedList<String> options = new LinkedList<>(); for (String s : args.saslOptionArg.getValues()) { int equalPos = s.indexOf('='); if (equalPos <= 0) { LocalizableMessage message = ERR_LDAP_CONN_CANNOT_PARSE_SASL_OPTION.get(s); err.println(wrapText(message, MAX_LINE_WIDTH)); throw new ArgumentException(message); printAndThrowException(err, ERR_LDAP_CONN_CANNOT_PARSE_SASL_OPTION.get(s)); } else { String name = s.substring(0, equalPos); if (name.equalsIgnoreCase("mech")) String name = s.substring(0, equalPos); if ("mech".equalsIgnoreCase(name)) { mechanism = s; } @@ -275,13 +256,10 @@ if (mechanism == null) { LocalizableMessage message = ERR_LDAP_CONN_NO_SASL_MECHANISM.get(); err.println(wrapText(message, MAX_LINE_WIDTH)); throw new ArgumentException(message); printAndThrowException(err, ERR_LDAP_CONN_NO_SASL_MECHANISM.get()); } connectionOptions.setSASLMechanism(mechanism); for (String option : options) { connectionOptions.addSASLProperty(option); @@ -290,114 +268,123 @@ int timeout = args.connectTimeoutArg.getIntValue(); final String passwordValue = getPasswordValue( args.bindPasswordArg, args.bindPasswordFileArg, args.bindDnArg, out, err); return connect( args.hostNameArg.getValue(), args.portArg.getIntValue(), args.bindDnArg.getValue(), getPasswordValue(args.bindPasswordArg, args.bindPasswordFileArg, args.bindDnArg, out, err), passwordValue, connectionOptions, timeout, out, err); } /** * Creates a connection using a console interaction that will be used * to potentially interact with the user to prompt for necessary * information for establishing the connection. * * @param ui user interaction for prompting the user * @param out stream to write messages * @param err stream to write error messages * @return LDAPConnection created by this class from parsed arguments * @throws LDAPConnectionException if there was a problem connecting * to the server indicated by the input arguments */ public LDAPConnection connect(LDAPConnectionConsoleInteraction ui, PrintStream out, PrintStream err) throws LDAPConnectionException private void printAndThrowException(PrintStream err, LocalizableMessage message) throws ArgumentException { LDAPConnection connection = null; try { err.println(wrapText(message, MAX_LINE_WIDTH)); throw new ArgumentException(message); } /** * Creates a connection using a console interaction that will be used to * potentially interact with the user to prompt for necessary information for * establishing the connection. * * @param ui * user interaction for prompting the user * @param out * stream to write messages * @param err * stream to write error messages * @return LDAPConnection created by this class from parsed arguments * @throws LDAPConnectionException * if there was a problem connecting to the server indicated by the * input arguments */ public LDAPConnection connect(LDAPConnectionConsoleInteraction ui, PrintStream out, PrintStream err) throws LDAPConnectionException { try { ui.run(); LDAPConnectionOptions options = new LDAPConnectionOptions(); options.setVersionNumber(3); connection = connect( ui.getHostName(), ui.getPortNumber(), ui.getBindDN(), ui.getBindPassword(), ui.populateLDAPOptions(options), ui.getConnectTimeout(), out, err); } catch (ArgumentException | OpenDsException e) { if ((e.getCause() != null) && (e.getCause().getCause() != null) && e.getCause().getCause() instanceof SSLException) { return connect(ui.getHostName(), ui.getPortNumber(), ui.getBindDN(), ui.getBindPassword(), ui.populateLDAPOptions(options), ui.getConnectTimeout(), out, err); } catch (ArgumentException | OpenDsException e) { if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof SSLException) { err.println(ERR_TASKINFO_LDAP_EXCEPTION_SSL.get(ui.getHostName(), ui.getPortNumber())); } else { } else { err.println(e.getMessageObject()); } } return connection; return null; } /** * Creates a connection from information provided. * * @param host of the server * @param port of the server * @param bindDN with which to connect * @param bindPw with which to connect * @param options with which to connect * @param out stream to write messages * @param err stream to write error messages * @param host * of the server * @param port * of the server * @param bindDN * with which to connect * @param bindPw * with which to connect * @param options * with which to connect * @param out * stream to write messages * @param err * stream to write error messages * @return LDAPConnection created by this class from parsed arguments * @throws LDAPConnectionException if there was a problem connecting * to the server indicated by the input arguments * @throws LDAPConnectionException * if there was a problem connecting to the server indicated by the * input arguments */ public LDAPConnection connect(String host, int port, String bindDN, String bindPw, LDAPConnectionOptions options, PrintStream out, PrintStream err) throws LDAPConnectionException public LDAPConnection connect(String host, int port, String bindDN, String bindPw, LDAPConnectionOptions options, PrintStream out, PrintStream err) throws LDAPConnectionException { return connect(host, port, bindDN, bindPw, options, 0, out, err); } /** * Creates a connection from information provided. * * @param host of the server * @param port of the server * @param bindDN with which to connect * @param bindPw with which to connect * @param options with which to connect * @param timeout the timeout to establish the connection in milliseconds. * Use {@code 0} to express no timeout * @param out stream to write messages * @param err stream to write error messages * @param host * of the server * @param port * of the server * @param bindDN * with which to connect * @param bindPw * with which to connect * @param options * with which to connect * @param timeout * the timeout to establish the connection in milliseconds. Use * {@code 0} to express no timeout * @param out * stream to write messages * @param err * stream to write error messages * @return LDAPConnection created by this class from parsed arguments * @throws LDAPConnectionException if there was a problem connecting * to the server indicated by the input arguments * @throws LDAPConnectionException * if there was a problem connecting to the server indicated by the * input arguments */ public LDAPConnection connect(String host, int port, String bindDN, String bindPw, LDAPConnectionOptions options, int timeout, PrintStream out, PrintStream err) throws LDAPConnectionException public LDAPConnection connect(String host, int port, String bindDN, String bindPw, LDAPConnectionOptions options, int timeout, PrintStream out, PrintStream err) throws LDAPConnectionException { // Attempt to connect and authenticate to the Directory Server. AtomicInteger nextMessageID = new AtomicInteger(1); LDAPConnection connection = new LDAPConnection( host, port, options, out, err); LDAPConnection connection = new LDAPConnection(host, port, options, out, err); connection.connectToHost(bindDN, bindPw, nextMessageID, timeout); return connection; } @@ -406,29 +393,31 @@ * * @return arguments for this parser. */ public SecureConnectionCliArgs getArguments() { public SecureConnectionCliArgs getArguments() { return args; } /** * Commodity method that retrieves the password value analyzing the contents * of a string argument and of a file based argument. It assumes that the * arguments have already been parsed and validated. * If the string is a dash, or no password is available, it will prompt for * it on the command line. * of a string argument and of a file based argument. It assumes that the * arguments have already been parsed and validated. If the string is a dash, * or no password is available, it will prompt for it on the command line. * * @param bindPwdArg the string argument for the password. * @param bindPwdFileArg the file based argument for the password. * @param bindDnArg the string argument for the bindDN. * @param out stream to write message. * @param err stream to write error message. * @param bindPwdArg * the string argument for the password. * @param bindPwdFileArg * the file based argument for the password. * @param bindDnArg * the string argument for the bindDN. * @param out * stream to write message. * @param err * stream to write error message. * @return the password value. */ public static String getPasswordValue(StringArgument bindPwdArg, FileBasedArgument bindPwdFileArg, StringArgument bindDnArg, PrintStream out, PrintStream err) public static String getPasswordValue(StringArgument bindPwdArg, FileBasedArgument bindPwdFileArg, StringArgument bindDnArg, PrintStream out, PrintStream err) { try { @@ -443,28 +432,30 @@ /** * Commodity method that retrieves the password value analyzing the contents * of a string argument and of a file based argument. It assumes that the * arguments have already been parsed and validated. * If the string is a dash, or no password is available, it will prompt for * it on the command line. * of a string argument and of a file based argument. It assumes that the * arguments have already been parsed and validated. If the string is a dash, * or no password is available, it will prompt for it on the command line. * * @param bindPassword the string argument for the password. * @param bindPasswordFile the file based argument for the password. * @param bindDNValue the string value for the bindDN. * @param out stream to write message. * @param err stream to write error message. * @param bindPassword * the string argument for the password. * @param bindPasswordFile * the file based argument for the password. * @param bindDNValue * the string value for the bindDN. * @param out * stream to write message. * @param err * stream to write error message. * @return the password value. * @throws ClientException if the password cannot be read * @throws ClientException * if the password cannot be read */ public static String getPasswordValue(StringArgument bindPassword, FileBasedArgument bindPasswordFile, String bindDNValue, PrintStream out, PrintStream err) throws ClientException public static String getPasswordValue(StringArgument bindPassword, FileBasedArgument bindPasswordFile, String bindDNValue, PrintStream out, PrintStream err) throws ClientException { String bindPasswordValue = bindPassword.getValue(); if ("-".equals(bindPasswordValue) || (!bindPasswordFile.isPresent() && bindDNValue != null && bindPasswordValue == null)) || (!bindPasswordFile.isPresent() && bindDNValue != null && bindPasswordValue == null)) { // read the password from the stdin. out.print(INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDNValue)); @@ -473,8 +464,7 @@ // an empty password to the server. while (pwChars.length == 0) { err.println(wrapText(INFO_LDAPAUTH_NON_EMPTY_PASSWORD.get(), MAX_LINE_WIDTH)); err.println(wrapText(INFO_LDAPAUTH_NON_EMPTY_PASSWORD.get(), MAX_LINE_WIDTH)); out.print(INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDNValue)); pwChars = ConsoleApplication.readPassword(); } @@ -488,15 +478,19 @@ return bindPasswordValue; } private void addLdapConnectionArguments(ArgumentGroup argGroup, boolean alwaysSSL) { private void addLdapConnectionArguments(ArgumentGroup argGroup, boolean alwaysSSL) { args = new SecureConnectionCliArgs(alwaysSSL); try { LinkedHashSet<Argument> argSet = args.createGlobalArguments(); for (Argument arg : argSet) { try { Set<Argument> argSet = args.createGlobalArguments(); for (Argument arg : argSet) { addArgument(arg, argGroup); } } catch (ArgumentException ae) { catch (ArgumentException ae) { ae.printStackTrace(); // Should never happen } }