예제 #1
0
  /**
   * Test entry.
   *
   * @throws Exception If the test failed unexpectedly.
   */
  @Test()
  public void testEntryToAndFromDatabase() throws Exception {
    // Make sure that the server is up and running.
    TestCaseUtils.startServer();

    // Convert the test LDIF string to a byte array
    byte[] originalLDIFBytes = StaticUtils.getBytes(ldifString);

    LDIFReader reader =
        new LDIFReader(new LDIFImportConfig(new ByteArrayInputStream(originalLDIFBytes)));

    Entry entryBefore, entryAfter;
    while ((entryBefore = reader.readEntry(false)) != null) {
      ByteString bytes = ID2Entry.entryToDatabase(entryBefore, new DataConfig(false, false, null));

      entryAfter = ID2Entry.entryFromDatabase(bytes, DirectoryServer.getDefaultCompressedSchema());

      // check DN and number of attributes
      assertEquals(entryBefore.getAttributes().size(), entryAfter.getAttributes().size());

      assertEquals(entryBefore.getDN(), entryAfter.getDN());

      // check the object classes were not changed
      for (String ocBefore : entryBefore.getObjectClasses().values()) {
        ObjectClass objectClass = DirectoryServer.getObjectClass(ocBefore.toLowerCase());
        if (objectClass == null) {
          objectClass = DirectoryServer.getDefaultObjectClass(ocBefore);
        }
        String ocAfter = entryAfter.getObjectClasses().get(objectClass);

        assertEquals(ocBefore, ocAfter);
      }

      // check the user attributes were not changed
      for (AttributeType attrType : entryBefore.getUserAttributes().keySet()) {
        List<Attribute> listBefore = entryBefore.getAttribute(attrType);
        List<Attribute> listAfter = entryAfter.getAttribute(attrType);

        assertTrue(listAfter != null);

        assertEquals(listBefore.size(), listAfter.size());

        for (Attribute attrBefore : listBefore) {
          boolean found = false;

          for (Attribute attrAfter : listAfter) {
            if (attrAfter.optionsEqual(attrBefore.getOptions())) {
              // Found the corresponding attribute

              assertEquals(attrBefore, attrAfter);
              found = true;
            }
          }

          assertTrue(found);
        }
      }
    }
    reader.close();
  }
  /** {@inheritDoc} */
  @Override
  public void initializeSASLMechanismHandler(ExternalSASLMechanismHandlerCfg configuration)
      throws ConfigException, InitializationException {
    configuration.addExternalChangeListener(this);
    currentConfig = configuration;

    // See if we should attempt to validate client certificates against those in
    // the corresponding user's entry.
    switch (configuration.getCertificateValidationPolicy()) {
      case NEVER:
        validationPolicy = CertificateValidationPolicy.NEVER;
        break;
      case IFPRESENT:
        validationPolicy = CertificateValidationPolicy.IFPRESENT;
        break;
      case ALWAYS:
        validationPolicy = CertificateValidationPolicy.ALWAYS;
        break;
    }

    // Get the attribute type to use for validating the certificates.  If none
    // is provided, then default to the userCertificate type.
    certificateAttributeType = configuration.getCertificateAttribute();
    if (certificateAttributeType == null) {
      certificateAttributeType =
          DirectoryServer.getAttributeType(DEFAULT_VALIDATION_CERT_ATTRIBUTE, true);
    }

    DirectoryServer.registerSASLMechanismHandler(SASL_MECHANISM_EXTERNAL, this);
  }
  /** {@inheritDoc} */
  public void initializeSyntax(AttributeSyntaxCfg configuration) throws ConfigException {
    defaultApproximateMatchingRule =
        DirectoryServer.getApproximateMatchingRule(AMR_DOUBLE_METAPHONE_OID);
    if (defaultApproximateMatchingRule == null) {
      logError(
          ERR_ATTR_SYNTAX_UNKNOWN_APPROXIMATE_MATCHING_RULE.get(
              AMR_DOUBLE_METAPHONE_OID, SYNTAX_PRESENTATION_ADDRESS_NAME));
    }

    defaultEqualityMatchingRule = DirectoryServer.getEqualityMatchingRule(EMR_CASE_IGNORE_OID);
    if (defaultEqualityMatchingRule == null) {
      logError(
          ERR_ATTR_SYNTAX_UNKNOWN_EQUALITY_MATCHING_RULE.get(
              EMR_CASE_IGNORE_OID, SYNTAX_PRESENTATION_ADDRESS_NAME));
    }

    defaultOrderingMatchingRule = DirectoryServer.getOrderingMatchingRule(OMR_CASE_IGNORE_OID);
    if (defaultOrderingMatchingRule == null) {
      logError(
          ERR_ATTR_SYNTAX_UNKNOWN_ORDERING_MATCHING_RULE.get(
              OMR_CASE_IGNORE_OID, SYNTAX_PRESENTATION_ADDRESS_NAME));
    }

    defaultSubstringMatchingRule = DirectoryServer.getSubstringMatchingRule(SMR_CASE_IGNORE_OID);
    if (defaultSubstringMatchingRule == null) {
      logError(
          ERR_ATTR_SYNTAX_UNKNOWN_SUBSTRING_MATCHING_RULE.get(
              SMR_CASE_IGNORE_OID, SYNTAX_PRESENTATION_ADDRESS_NAME));
    }
  }
예제 #4
0
  /**
   * Generates an entry for a backup directory based on the provided DN. The DN must contain an RDN
   * component that specifies the path to the backup directory, and that directory must exist and be
   * a valid backup directory.
   *
   * @param entryDN The DN of the backup directory entry to retrieve.
   * @return The requested backup directory entry.
   * @throws DirectoryException If the specified directory does not exist or is not a valid backup
   *     directory, or if the DN does not specify any backup directory.
   */
  private Entry getBackupDirectoryEntry(DN entryDN) throws DirectoryException {
    // Make sure that the DN specifies a backup directory.
    AttributeType t = DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
    AttributeValue v = entryDN.getRDN().getAttributeValue(t);
    if (v == null) {
      Message message = ERR_BACKUP_DN_DOES_NOT_SPECIFY_DIRECTORY.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message, backupBaseDN, null);
    }

    // Get a handle to the backup directory and the information that it
    // contains.
    BackupDirectory backupDirectory;
    try {
      backupDirectory = BackupDirectory.readBackupDirectoryDescriptor(v.getValue().toString());
    } catch (ConfigException ce) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, ce);
      }

      Message message =
          ERR_BACKUP_INVALID_BACKUP_DIRECTORY.get(String.valueOf(entryDN), ce.getMessage());
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
    } catch (Exception e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }

      Message message = ERR_BACKUP_ERROR_GETTING_BACKUP_DIRECTORY.get(getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }

    // Construct the backup directory entry to return.
    LinkedHashMap<ObjectClass, String> ocMap = new LinkedHashMap<ObjectClass, String>(2);
    ocMap.put(DirectoryServer.getTopObjectClass(), OC_TOP);

    ObjectClass backupDirOC = DirectoryServer.getObjectClass(OC_BACKUP_DIRECTORY, true);
    ocMap.put(backupDirOC, OC_BACKUP_DIRECTORY);

    LinkedHashMap<AttributeType, List<Attribute>> opAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>(0);
    LinkedHashMap<AttributeType, List<Attribute>> userAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>(3);

    ArrayList<Attribute> attrList = new ArrayList<Attribute>(1);
    attrList.add(Attributes.create(t, v));
    userAttrs.put(t, attrList);

    t = DirectoryServer.getAttributeType(ATTR_BACKUP_BACKEND_DN, true);
    attrList = new ArrayList<Attribute>(1);
    attrList.add(
        Attributes.create(
            t, AttributeValues.create(t, backupDirectory.getConfigEntryDN().toString())));
    userAttrs.put(t, attrList);

    Entry e = new Entry(entryDN, ocMap, userAttrs, opAttrs);
    e.processVirtualAttributes();
    return e;
  }
  /**
   * Tests the use of the StartTLS extended operation to communicate with the server in conjunction
   * with SASL EXTERNAL authentication and using a client trust store to validate the server
   * certificate.
   *
   * @throws Exception If an unexpected problem occurs.
   */
  @Test()
  public void testStartTLSExternalAuthTrustStore() throws Exception {
    TestCaseUtils.initializeTestBackend(true);

    Entry e =
        TestCaseUtils.makeEntry(
            "dn: cn=Test User,o=test",
            "objectClass: top",
            "objectClass: person",
            "objectClass: organizationalPerson",
            "objectClass: inetOrgPerson",
            "cn: Test User",
            "givenName: Test",
            "sn: User");

    InternalClientConnection conn = InternalClientConnection.getRootConnection();
    AddOperation addOperation =
        conn.processAdd(
            e.getDN(), e.getObjectClasses(), e.getUserAttributes(), e.getOperationalAttributes());
    assertEquals(addOperation.getResultCode(), ResultCode.SUCCESS);

    String keyStorePath =
        DirectoryServer.getInstanceRoot()
            + File.separator
            + "config"
            + File.separator
            + "client.keystore";
    String trustStorePath =
        DirectoryServer.getInstanceRoot()
            + File.separator
            + "config"
            + File.separator
            + "client.truststore";

    String[] args = {
      "--noPropertiesFile",
      "-h",
      "127.0.0.1",
      "-p",
      String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-q",
      "-K",
      keyStorePath,
      "-W",
      "password",
      "-P",
      trustStorePath,
      "-r",
      "-b",
      "",
      "-s",
      "base",
      "(objectClass=*)"
    };

    assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
  }
예제 #6
0
  private SSLContext createSSLContext(LDAPConnectionHandlerCfg config) throws DirectoryException {
    try {
      DN keyMgrDN = config.getKeyManagerProviderDN();
      KeyManagerProvider<?> keyManagerProvider = DirectoryServer.getKeyManagerProvider(keyMgrDN);
      if (keyManagerProvider == null) {
        logger.error(ERR_NULL_KEY_PROVIDER_MANAGER, keyMgrDN, friendlyName);
        disableAndWarnIfUseSSL(config);
        keyManagerProvider = new NullKeyManagerProvider();
        // The SSL connection is unusable without a key manager provider
      } else if (!keyManagerProvider.containsAtLeastOneKey()) {
        logger.error(ERR_INVALID_KEYSTORE, friendlyName);
        disableAndWarnIfUseSSL(config);
      }

      final SortedSet<String> aliases = new TreeSet<>(config.getSSLCertNickname());
      final KeyManager[] keyManagers;
      if (aliases.isEmpty()) {
        keyManagers = keyManagerProvider.getKeyManagers();
      } else {
        final Iterator<String> it = aliases.iterator();
        while (it.hasNext()) {
          if (!keyManagerProvider.containsKeyWithAlias(it.next())) {
            logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, aliases, friendlyName);
            it.remove();
          }
        }

        if (aliases.isEmpty()) {
          disableAndWarnIfUseSSL(config);
        }
        keyManagers =
            SelectableCertificateKeyManager.wrap(
                keyManagerProvider.getKeyManagers(), aliases, friendlyName);
      }

      DN trustMgrDN = config.getTrustManagerProviderDN();
      TrustManagerProvider<?> trustManagerProvider =
          DirectoryServer.getTrustManagerProvider(trustMgrDN);
      if (trustManagerProvider == null) {
        trustManagerProvider = new NullTrustManagerProvider();
      }

      SSLContext sslContext = SSLContext.getInstance(SSL_CONTEXT_INSTANCE_NAME);
      sslContext.init(keyManagers, trustManagerProvider.getTrustManagers(), null);
      return sslContext;
    } catch (Exception e) {
      logger.traceException(e);
      ResultCode resCode = DirectoryServer.getServerErrorResultCode();
      LocalizableMessage message =
          ERR_CONNHANDLER_SSL_CANNOT_INITIALIZE.get(getExceptionMessage(e));
      throw new DirectoryException(resCode, message, e);
    }
  }
예제 #7
0
  /** {@inheritDoc} */
  @Override()
  public void finalizeBackend() {
    // Deregister as a change listener.
    cfg.removeLocalDBChangeListener(this);

    // Deregister our base DNs.
    for (DN dn : rootContainer.getBaseDNs()) {
      try {
        DirectoryServer.deregisterBaseDN(dn);
      } catch (Exception e) {
        if (debugEnabled()) {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
      }
    }

    DirectoryServer.deregisterMonitorProvider(rootContainerMonitor);
    DirectoryServer.deregisterMonitorProvider(diskMonitor);

    // We presume the server will prevent more operations coming into this
    // backend, but there may be existing operations already in the
    // backend. We need to wait for them to finish.
    waitUntilQuiescent();

    // Close the database.
    try {
      rootContainer.close();
      rootContainer = null;
    } catch (DatabaseException e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      Message message = ERR_JEB_DATABASE_EXCEPTION.get(e.getMessage());
      logError(message);
    }

    // Checksum this db environment and register its offline state id/checksum.
    DirectoryServer.registerOfflineBackendStateID(this.getBackendID(), checksumDbEnv());

    // Deregister the alert generator.
    DirectoryServer.deregisterAlertGenerator(this);

    // Make sure the thread counts are zero for next initialization.
    threadTotalCount.set(0);
    threadWriteCount.set(0);

    // Log an informational message.
    Message message = NOTE_BACKEND_OFFLINE.get(cfg.getBackendId());
    logError(message);
  }
예제 #8
0
  @Override
  public void finalizeConnectionHandler(LocalizableMessage finalizeReason) {
    shutdownRequested = true;
    // Unregister this as a change listener.
    currentConfig.removeHTTPChangeListener(this);

    if (connMonitor != null) {
      DirectoryServer.deregisterMonitorProvider(connMonitor);
    }

    if (statTracker != null) {
      DirectoryServer.deregisterMonitorProvider(statTracker);
    }
  }
예제 #9
0
 /**
  * Gracefully shuts down the embedded OpenDJ instance.
  *
  * @param reason string representing reason why shutdown was called.
  * @throws Exception on encountering errors.
  */
 public static void shutdownServer(String reason) throws Exception {
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   if (isStarted()) {
     debug.message("EmbeddedOpenDS.shutdown server...");
     DirectoryServer.shutDown("com.sun.identity.setup.EmbeddedOpenDS", Message.EMPTY);
     int sleepcount = 0;
     while (DirectoryServer.isRunning() && (sleepcount < 60)) {
       sleepcount++;
       Thread.sleep(1000);
     }
     serverStarted = false;
     debug.message("EmbeddedOpenDS.shutdown server success.");
   }
 }
예제 #10
0
  // We initialize these for each new AciHandler so that we can clear
  // out the stale references that can occur during an in-core restart.
  private static void initStatics() {
    if ((aciType = DirectoryServer.getAttributeType("aci")) == null) {
      aciType = DirectoryServer.getDefaultAttributeType("aci");
    }

    if ((globalAciType = DirectoryServer.getAttributeType(ATTR_AUTHZ_GLOBAL_ACI)) == null) {
      globalAciType = DirectoryServer.getDefaultAttributeType(ATTR_AUTHZ_GLOBAL_ACI);
    }

    if ((debugSearchIndex =
            DirectoryServer.getAttributeType(EntryContainer.ATTR_DEBUG_SEARCH_INDEX))
        == null) {
      debugSearchIndex =
          DirectoryServer.getDefaultAttributeType(EntryContainer.ATTR_DEBUG_SEARCH_INDEX);
    }

    if ((refAttrType = DirectoryServer.getAttributeType(ATTR_REFERRAL_URL)) == null) {
      refAttrType = DirectoryServer.getDefaultAttributeType(ATTR_REFERRAL_URL);
    }
    try {
      debugSearchIndexDN = DN.decode("cn=debugsearch");
    } catch (DirectoryException ex) {
      // Should never happen.
    }
  }
예제 #11
0
  private SSLContext createSSLContext(HTTPConnectionHandlerCfg config) throws Exception {
    if (!config.isUseSSL()) {
      return null;
    }

    DN keyMgrDN = config.getKeyManagerProviderDN();
    KeyManagerProvider<?> keyManagerProvider = DirectoryServer.getKeyManagerProvider(keyMgrDN);
    if (keyManagerProvider == null) {
      logger.error(ERR_NULL_KEY_PROVIDER_MANAGER, keyMgrDN, friendlyName);
      logger.warn(INFO_DISABLE_CONNECTION, friendlyName);
      keyManagerProvider = new NullKeyManagerProvider();
      enabled = false;
    } else if (!keyManagerProvider.containsAtLeastOneKey()) {
      logger.error(ERR_INVALID_KEYSTORE, friendlyName);
      logger.warn(INFO_DISABLE_CONNECTION, friendlyName);
      enabled = false;
    }

    final SortedSet<String> aliases = new TreeSet<>(config.getSSLCertNickname());
    final KeyManager[] keyManagers;
    if (aliases.isEmpty()) {
      keyManagers = keyManagerProvider.getKeyManagers();
    } else {
      final Iterator<String> it = aliases.iterator();
      while (it.hasNext()) {
        if (!keyManagerProvider.containsKeyWithAlias(it.next())) {
          logger.error(ERR_KEYSTORE_DOES_NOT_CONTAIN_ALIAS, aliases, friendlyName);
          it.remove();
        }
      }
      if (aliases.isEmpty()) {
        logger.warn(INFO_DISABLE_CONNECTION, friendlyName);
        enabled = false;
      }
      keyManagers =
          SelectableCertificateKeyManager.wrap(keyManagerProvider.getKeyManagers(), aliases);
    }

    DN trustMgrDN = config.getTrustManagerProviderDN();
    TrustManagerProvider<?> trustManagerProvider =
        DirectoryServer.getTrustManagerProvider(trustMgrDN);
    if (trustManagerProvider == null) {
      trustManagerProvider = new NullTrustManagerProvider();
    }

    SSLContext sslContext = SSLContext.getInstance(SSL_CONTEXT_INSTANCE_NAME);
    sslContext.init(keyManagers, trustManagerProvider.getTrustManagers(), null);
    return sslContext;
  }
예제 #12
0
  @Override
  public synchronized void openBackend() throws ConfigException, InitializationException {
    baseDNSet = new HashSet<>();
    Collections.addAll(baseDNSet, baseDNs);

    // Register base DNs.
    for (DN dn : baseDNs) {
      try {
        DirectoryServer.registerBaseDN(dn, this, false);
      } catch (Exception e) {
        logger.traceException(e);

        LocalizableMessage message =
            ERR_BACKEND_CANNOT_REGISTER_BASEDN.get(dn, getExceptionMessage(e));
        throw new InitializationException(message, e);
      }
    }

    // Initialize null entry object classes.
    objectClasses = new HashMap<>();

    String topOCName = "top";
    ObjectClass topOC = DirectoryServer.getObjectClass(topOCName);
    if (topOC == null) {
      throw new InitializationException(
          LocalizableMessage.raw(
              "Unable to locate " + topOCName + " objectclass in the current server schema"));
    }
    objectClasses.put(topOC, topOCName);

    String nulOCName = "nullbackendobject";
    ObjectClass nulOC = DirectoryServer.getDefaultObjectClass(nulOCName);
    try {
      DirectoryServer.registerObjectClass(nulOC, false);
    } catch (DirectoryException de) {
      logger.traceException(de);
      throw new InitializationException(de.getMessageObject());
    }
    objectClasses.put(nulOC, nulOCName);

    String extOCName = "extensibleobject";
    ObjectClass extOC = DirectoryServer.getObjectClass(extOCName);
    if (extOC == null) {
      throw new InitializationException(
          LocalizableMessage.raw(
              "Unable to locate " + extOCName + " objectclass in the current server schema"));
    }
    objectClasses.put(extOC, extOCName);
  }
 /** {@inheritDoc} */
 @Override
 public MemberList getMembers() throws DirectoryException {
   Group targetGroup = DirectoryServer.getGroupManager().getGroupInstance(targetGroupDN);
   if (targetGroup == null) {
     LocalizableMessage message =
         ERR_VIRTUAL_STATIC_GROUP_NO_TARGET_GROUP.get(targetGroupDN, groupEntryDN);
     throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
   } else if (targetGroup instanceof VirtualStaticGroup) {
     LocalizableMessage message =
         ERR_VIRTUAL_STATIC_GROUP_TARGET_CANNOT_BE_VIRTUAL.get(groupEntryDN, targetGroupDN);
     throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
   } else {
     return targetGroup.getMembers();
   }
 }
예제 #14
0
  /**
   * Returns the path of the installation of the directory server. Note that this method assumes
   * that this code is being run locally.
   *
   * @return the path of the installation of the directory server.
   */
  static String getInstallPathFromClasspath() {
    String installPath = DirectoryServer.getServerRoot();
    if (installPath != null) {
      return installPath;
    }

    /* Get the install path from the Class Path */
    final String sep = System.getProperty("path.separator");
    final String[] classPaths = System.getProperty("java.class.path").split(sep);
    String path = getInstallPath(classPaths);
    if (path != null) {
      final File f = new File(path).getAbsoluteFile();
      final File librariesDir = f.getParentFile();

      /*
       * Do a best effort to avoid having a relative representation (for
       * instance to avoid having ../../../).
       */
      try {
        installPath = librariesDir.getParentFile().getCanonicalPath();
      } catch (IOException ioe) {
        // Best effort
        installPath = librariesDir.getParent();
      }
    }
    return installPath;
  }
  /** {@inheritDoc} */
  public ConfigChangeResult applyConfigurationChange(
      ExternalSASLMechanismHandlerCfg configuration) {
    final ConfigChangeResult ccr = new ConfigChangeResult();

    // See if we should attempt to validate client certificates against those in
    // the corresponding user's entry.
    CertificateValidationPolicy newValidationPolicy = CertificateValidationPolicy.ALWAYS;
    switch (configuration.getCertificateValidationPolicy()) {
      case NEVER:
        newValidationPolicy = CertificateValidationPolicy.NEVER;
        break;
      case IFPRESENT:
        newValidationPolicy = CertificateValidationPolicy.IFPRESENT;
        break;
      case ALWAYS:
        newValidationPolicy = CertificateValidationPolicy.ALWAYS;
        break;
    }

    // Get the attribute type to use for validating the certificates.  If none
    // is provided, then default to the userCertificate type.
    AttributeType newCertificateType = configuration.getCertificateAttribute();
    if (newCertificateType == null) {
      newCertificateType =
          DirectoryServer.getAttributeType(DEFAULT_VALIDATION_CERT_ATTRIBUTE, true);
    }

    if (ccr.getResultCode() == ResultCode.SUCCESS) {
      validationPolicy = newValidationPolicy;
      certificateAttributeType = newCertificateType;
      currentConfig = configuration;
    }

    return ccr;
  }
  /**
   * Process this search operation against a local backend.
   *
   * @param wfe The local backend work-flow element.
   * @throws CanceledOperationException if this operation should be cancelled
   */
  public void processLocalSearch(LocalBackendWorkflowElement wfe)
      throws CanceledOperationException {
    this.backend = wfe.getBackend();
    this.clientConnection = getClientConnection();

    // Check for a request to cancel this operation.
    checkIfCanceled(false);

    try {
      BooleanHolder executePostOpPlugins = new BooleanHolder(false);
      processSearch(executePostOpPlugins);

      // Check for a request to cancel this operation.
      checkIfCanceled(false);

      // Invoke the post-operation search plugins.
      if (executePostOpPlugins.value) {
        PluginResult.PostOperation postOpResult =
            DirectoryServer.getPluginConfigManager().invokePostOperationSearchPlugins(this);
        if (!postOpResult.continueProcessing()) {
          setResultCode(postOpResult.getResultCode());
          appendErrorMessage(postOpResult.getErrorMessage());
          setMatchedDN(postOpResult.getMatchedDN());
          setReferralURLs(postOpResult.getReferralURLs());
        }
      }
    } finally {
      LocalBackendWorkflowElement.filterNonDisclosableMatchedDN(this);
    }
  }
  /** {@inheritDoc} */
  public void initializeSyntax(AttributeSyntaxCfg configuration) throws ConfigException {
    defaultEqualityMatchingRule = DirectoryServer.getEqualityMatchingRule(EMR_CASE_IGNORE_LIST_OID);
    if (defaultEqualityMatchingRule == null) {
      logError(
          ERR_ATTR_SYNTAX_UNKNOWN_EQUALITY_MATCHING_RULE.get(
              EMR_CASE_IGNORE_LIST_OID, SYNTAX_OTHER_MAILBOX_NAME));
    }

    defaultSubstringMatchingRule =
        DirectoryServer.getSubstringMatchingRule(SMR_CASE_IGNORE_LIST_OID);
    if (defaultSubstringMatchingRule == null) {
      logError(
          ERR_ATTR_SYNTAX_UNKNOWN_SUBSTRING_MATCHING_RULE.get(
              SMR_CASE_IGNORE_LIST_OID, SYNTAX_OTHER_MAILBOX_NAME));
    }
  }
  /**
   * Releases any resources held by the writer.
   *
   * @param shutdownWrapped If the wrapped writer should be closed as well.
   */
  public void shutdown(boolean shutdownWrapped) {
    stopRequested.set(true);

    // Wait for publisher thread to terminate
    while (writerThread != null && writerThread.isAlive()) {
      try {
        // Interrupt the thread if its blocking
        writerThread.interrupt();
        writerThread.join();
      } catch (InterruptedException ex) {
        // Ignore; we gotta wait..
      }
    }

    // The writer writerThread SHOULD have drained the queue.
    // If not, handle outstanding requests ourselves,
    // and push them to the writer.
    while (!queue.isEmpty()) {
      String message = queue.poll();
      writer.writeRecord(message);
    }

    // Shutdown the wrapped writer.
    if (shutdownWrapped && writer != null) writer.shutdown();

    DirectoryServer.deregisterShutdownListener(this);
  }
예제 #19
0
  /** {@inheritDoc} */
  @Override()
  public long numSubordinates(DN entryDN, boolean subtree) throws DirectoryException {
    EntryContainer ec;
    if (rootContainer != null) {
      ec = rootContainer.getEntryContainer(entryDN);
    } else {
      Message message = ERR_ROOT_CONTAINER_NOT_INITIALIZED.get(getBackendID());
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }

    if (ec == null) {
      return -1;
    }

    readerBegin();
    ec.sharedLock.lock();
    try {
      long count = ec.getNumSubordinates(entryDN, subtree);
      if (count == Long.MAX_VALUE) {
        // The index entry limit has exceeded and there is no count maintained.
        return -1;
      }
      return count;
    } catch (DatabaseException e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      throw createDirectoryException(e);
    } finally {
      ec.sharedLock.unlock();
      readerEnd();
    }
  }
예제 #20
0
  /** {@inheritDoc} */
  @Override()
  public Entry getEntry(DN entryDN) throws DirectoryException {
    readerBegin();

    EntryContainer ec;
    if (rootContainer != null) {
      ec = rootContainer.getEntryContainer(entryDN);
    } else {
      Message message = ERR_ROOT_CONTAINER_NOT_INITIALIZED.get(getBackendID());
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }

    ec.sharedLock.lock();
    Entry entry;
    try {
      entry = ec.getEntry(entryDN);
    } catch (DatabaseException e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      throw createDirectoryException(e);
    } finally {
      ec.sharedLock.unlock();
      readerEnd();
    }

    return entry;
  }
 /**
  * Retrieves the default ordering matching rule that will be used for attributes with this
  * syntax.
  *
  * @return The default ordering matching rule that will be used for attributes with this syntax,
  *     or <CODE>null</CODE> if ordering matches will not be allowed for this type by default.
  */
 @Override
 public OrderingMatchingRule getOrderingMatchingRule() {
   if (orderingMatchingRule == null) {
     orderingMatchingRule = DirectoryServer.getOrderingMatchingRule(OMR_CASE_IGNORE_OID);
   }
   return orderingMatchingRule;
 }
예제 #22
0
  /** {@inheritDoc} */
  @Override()
  public void replaceEntry(Entry oldEntry, Entry newEntry, ModifyOperation modifyOperation)
      throws DirectoryException, CanceledOperationException {
    checkDiskSpace(modifyOperation);
    writerBegin();

    DN entryDN = newEntry.getDN();
    EntryContainer ec;
    if (rootContainer != null) {
      ec = rootContainer.getEntryContainer(entryDN);
    } else {
      Message message = ERR_ROOT_CONTAINER_NOT_INITIALIZED.get(getBackendID());
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }

    ec.sharedLock.lock();

    try {
      ec.replaceEntry(oldEntry, newEntry, modifyOperation);
    } catch (DatabaseException e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      throw createDirectoryException(e);
    } finally {
      ec.sharedLock.unlock();
      writerEnd();
    }
  }
예제 #23
0
  /** {@inheritDoc} */
  @Override
  public ByteString encodePasswordWithScheme(ByteSequence plaintext) throws DirectoryException {
    StringBuilder buffer = new StringBuilder();
    buffer.append('{');
    buffer.append(STORAGE_SCHEME_NAME_SHA_1);
    buffer.append('}');

    // TODO: Can we avoid this copy?
    byte[] plaintextBytes = null;
    byte[] digestBytes;

    synchronized (digestLock) {
      try {
        plaintextBytes = plaintext.toByteArray();
        digestBytes = messageDigest.digest(plaintextBytes);
      } catch (Exception e) {
        logger.traceException(e);

        LocalizableMessage message =
            ERR_PWSCHEME_CANNOT_ENCODE_PASSWORD.get(CLASS_NAME, getExceptionMessage(e));
        throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message, e);
      } finally {
        if (plaintextBytes != null) {
          Arrays.fill(plaintextBytes, (byte) 0);
        }
      }
    }

    buffer.append(Base64.encode(digestBytes));

    return ByteString.valueOfUtf8(buffer);
  }
  /**
   * Test that various backup and restore task definitions complete with the expected state.
   *
   * @param taskEntry The task entry.
   * @param expectedState The expected completion state of the task.
   */
  @Test(dataProvider = "backups")
  public void testBackups(Entry taskEntry, TaskState expectedState) throws Exception {
    final int backupBeginCountStart = backupBeginCount.get();
    final int backupEndCountStart = backupEndCount.get();
    final int restoreBeginCountStart = restoreBeginCount.get();
    final int restoreEndCountStart = restoreEndCount.get();

    ObjectClass backupClass = DirectoryServer.getObjectClass("ds-task-backup", true);

    testTask(taskEntry, expectedState, 30);
    if (expectedState == TaskState.COMPLETED_SUCCESSFULLY
        || expectedState == TaskState.COMPLETED_WITH_ERRORS) {
      if (taskEntry.hasObjectClass(backupClass)) {
        // The backup task can back up multiple backends at the same time, so
        // we the count may be incremented by more than one in those cases.
        assertThat(backupBeginCount.get()).isGreaterThan(backupBeginCountStart);
        assertThat(backupEndCount.get()).isGreaterThan(backupEndCountStart);
        assertEquals(backupBeginCount.get(), backupEndCount.get());
      } else {
        assertEquals(restoreBeginCount.get(), restoreBeginCountStart + 1);
        assertEquals(restoreEndCount.get(), restoreEndCountStart + 1);
        assertEquals(restoreBeginCount.get(), restoreEndCount.get());
      }
    }
  }
예제 #25
0
  /**
   * Performs any initialization for this tag that may be needed while parsing a branch definition.
   *
   * @param templateFile The template file in which this tag is used.
   * @param branch The branch in which this tag is used.
   * @param arguments The set of arguments provided for this tag.
   * @param lineNumber The line number on which this tag appears in the template file.
   * @param warnings A list into which any appropriate warning messages may be placed.
   * @throws InitializationException If a problem occurs while initializing this tag.
   */
  public void initializeForBranch(
      TemplateFile templateFile,
      Branch branch,
      String[] arguments,
      int lineNumber,
      List<Message> warnings)
      throws InitializationException {
    if ((arguments.length < 1) || (arguments.length > 2)) {
      Message message =
          ERR_MAKELDIF_TAG_INVALID_ARGUMENT_RANGE_COUNT.get(
              getName(), lineNumber, 1, 2, arguments.length);
      throw new InitializationException(message);
    }

    String lowerName = toLowerCase(arguments[0]);
    AttributeType t = DirectoryServer.getAttributeType(lowerName, true);
    if (!branch.hasAttribute(t)) {
      Message message = ERR_MAKELDIF_TAG_UNDEFINED_ATTRIBUTE.get(arguments[0], lineNumber);
      throw new InitializationException(message);
    }

    if (arguments.length == 2) {
      assertionValue = arguments[1];
    } else {
      assertionValue = null;
    }
  }
예제 #26
0
  /** {@inheritDoc} */
  @Override()
  public void search(SearchOperation searchOperation)
      throws DirectoryException, CanceledOperationException {
    readerBegin();

    EntryContainer ec;
    if (rootContainer != null) {
      ec = rootContainer.getEntryContainer(searchOperation.getBaseDN());
    } else {
      Message message = ERR_ROOT_CONTAINER_NOT_INITIALIZED.get(getBackendID());
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message);
    }
    ec.sharedLock.lock();

    try {
      ec.search(searchOperation);
    } catch (DatabaseException e) {
      if (debugEnabled()) {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      throw createDirectoryException(e);
    } finally {
      ec.sharedLock.unlock();
      readerEnd();
    }
  }
  /**
   * Tests the use of the StartTLS extended operation to communicate with the server in conjunction
   * with no authentication and using a client trust store to validate the server certificate.
   */
  @Test()
  public void testStartTLSNoAuthTrustStore() {
    String trustStorePath =
        DirectoryServer.getInstanceRoot()
            + File.separator
            + "config"
            + File.separator
            + "client.truststore";

    String[] args = {
      "--noPropertiesFile",
      "-h",
      "127.0.0.1",
      "-p",
      String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-q",
      "-P",
      trustStorePath,
      "-b",
      "",
      "-s",
      "base",
      "(objectClass=*)"
    };

    assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
  }
예제 #28
0
  /** {@inheritDoc} */
  @Override
  public long getEntryCount() {
    int numEntries = 1;

    AttributeType backupPathType =
        DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);

    for (File f : backupDirectories) {
      try {
        // Check to see if the descriptor file exists.  If not, then skip this
        // backup directory.
        File descriptorFile = new File(f, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
        if (!descriptorFile.exists()) {
          continue;
        }

        DN backupDirDN = makeChildDN(backupBaseDN, backupPathType, f.getAbsolutePath());
        getBackupDirectoryEntry(backupDirDN);
        numEntries++;
      } catch (Exception e) {
      }
    }

    return numEntries;
  }
 /**
  * Retrieves the default substring matching rule that will be used for attributes with this
  * syntax.
  *
  * @return The default substring matching rule that will be used for attributes with this
  *     syntax, or <CODE>null</CODE> if substring matches will not be allowed for this type by
  *     default.
  */
 @Override
 public SubstringMatchingRule getSubstringMatchingRule() {
   if (substringMatchingRule == null) {
     substringMatchingRule = DirectoryServer.getSubstringMatchingRule(SMR_CASE_IGNORE_OID);
   }
   return substringMatchingRule;
 }
예제 #30
0
  /** {@inheritDoc} */
  @Override
  public Entry getEntry(DN entryDN) throws DirectoryException {
    // If the requested entry was null, then throw an exception.
    if (entryDN == null) {
      throw new DirectoryException(
          DirectoryServer.getServerErrorResultCode(),
          ERR_BACKEND_GET_ENTRY_NULL.get(getBackendID()));
    }

    // If the requested entry was the backend base entry, then retrieve it.
    if (entryDN.equals(backupBaseDN)) {
      return backupBaseEntry.duplicate(true);
    }

    // See if the requested entry was one level below the backend base entry.
    // If so, then it must point to a backup directory.  Otherwise, it must be
    // two levels below the backup base entry and must point to a specific
    // backup.
    DN parentDN = entryDN.getParentDNInSuffix();
    if (parentDN == null) {
      Message message = ERR_BACKUP_INVALID_BASE.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
    } else if (parentDN.equals(backupBaseDN)) {
      return getBackupDirectoryEntry(entryDN);
    } else if (backupBaseDN.equals(parentDN.getParentDNInSuffix())) {
      return getBackupEntry(entryDN);
    } else {
      Message message = ERR_BACKUP_INVALID_BASE.get(String.valueOf(entryDN));
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message, backupBaseDN, null);
    }
  }