Example #1
0
  /**
   * Constructs a virtual list.
   *
   * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
   * version 3 and upper param base the base distinguished name to search from param filter search
   * filter specifying the search criteria param attrs list of attributes that you want returned in
   * the search results param sortKey the attribute to sort by param pageSize the size of a page.
   * There is a 3*pageSize buffer maintained so pageUp and pageDown won't invoke fetch from ldap
   * server
   */
  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String sortKey,
      int pageSize)
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs sortKey pageSize filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs)
            + " pageSize "
            + pageSize);
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    setSortKey(sortKey);
    setPageSize(pageSize);
  }
 public IDescriptor getConfigDescriptor(Locale locale, String name) {
   if (name.equals(CONFIG_CRITICAL)) {
     return new Descriptor(
         IDescriptor.BOOLEAN, null, "false", CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
   } else if (name.equals(CONFIG_OIDS)) {
     return new Descriptor(
         IDescriptor.STRING, null, null, CMS.getUserMessage(locale, "CMS_PROFILE_OIDS"));
   }
   return null;
 }
 public IDescriptor getValueDescriptor(Locale locale, String name) {
   if (name.equals(VAL_CRITICAL)) {
     return new Descriptor(
         IDescriptor.BOOLEAN, null, "false", CMS.getUserMessage(locale, "CMS_PROFILE_CRITICAL"));
   } else if (name.equals(VAL_OIDS)) {
     return new Descriptor(
         IDescriptor.STRING_LIST, null, null, CMS.getUserMessage(locale, "CMS_PROFILE_OIDS"));
   } else {
     return null;
   }
 }
  public String getValue(String name, Locale locale, X509CertInfo info) throws EPropertyException {
    if (name == null) {
      throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
    }

    ExtendedKeyUsageExtension ext =
        (ExtendedKeyUsageExtension) getExtension(ExtendedKeyUsageExtension.OID, info);

    if (ext == null) {
      try {
        populate(null, info);

      } catch (EProfileException e) {
        throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
      }
    }

    if (name.equals(VAL_CRITICAL)) {
      ext = (ExtendedKeyUsageExtension) getExtension(ExtendedKeyUsageExtension.OID, info);

      if (ext == null) {
        return null;
      }
      if (ext.isCritical()) {
        return "true";
      } else {
        return "false";
      }
    } else if (name.equals(VAL_OIDS)) {
      ext = (ExtendedKeyUsageExtension) getExtension(ExtendedKeyUsageExtension.OID, info);
      StringBuffer sb = new StringBuffer();
      if (ext == null) {
        return "";
      }
      Enumeration<ObjectIdentifier> e = ext.getOIDs();

      while (e.hasMoreElements()) {
        ObjectIdentifier oid = e.nextElement();

        if (!sb.toString().equals("")) {
          sb.append(",");
        }
        sb.append(oid.toString());
      }
      return sb.toString();
    } else {
      throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
    }
  }
  public void setValue(String name, Locale locale, X509CertInfo info, String value)
      throws EPropertyException {
    ExtendedKeyUsageExtension ext = null;

    ext = (ExtendedKeyUsageExtension) getExtension(ExtendedKeyUsageExtension.OID, info);

    if (ext == null) {
      try {
        populate(null, info);

      } catch (EProfileException e) {
        throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
      }
    }
    if (name == null) {
      throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
    }
    if (name.equals(VAL_CRITICAL)) {
      ext = (ExtendedKeyUsageExtension) getExtension(ExtendedKeyUsageExtension.OID, info);
      boolean val = Boolean.valueOf(value).booleanValue();

      if (ext == null) {
        return;
      }
      ext.setCritical(val);
    } else if (name.equals(VAL_OIDS)) {
      ext = (ExtendedKeyUsageExtension) getExtension(ExtendedKeyUsageExtension.OID, info);
      //		ext.deleteAllOIDs();
      StringTokenizer st = new StringTokenizer(value, ",");

      if (ext == null) {
        return;
      }
      while (st.hasMoreTokens()) {
        String oid = st.nextToken();

        ext.addOID(new ObjectIdentifier(oid));
      }
    } else {
      throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
    }
    try {
      replaceExtension(ExtendedKeyUsageExtension.OID, ext, info);
    } catch (EProfileException e) {
      CMS.debug("ExtendedKeyUsageExtDefault: setValue " + e.toString());
      throw new EPropertyException(CMS.getUserMessage(locale, "CMS_INVALID_PROPERTY", name));
    }
  }
Example #6
0
  /**
   * set the sort key
   *
   * @param sortKey the attributes to sort by
   */
  public void setSortKey(String[] sortKeys) throws EBaseException {
    if (sortKeys == null) throw new EBaseException("sort keys cannot be null");
    try {
      mKeys = new LDAPSortKey[sortKeys.length];
      String la[] = null;
      synchronized (this) {
        la = mRegistry.getLDAPAttributes(sortKeys);
      }

      for (int j = 0; j < sortKeys.length; j++) {
        mKeys[j] = new LDAPSortKey(la[j]);
      }
    } catch (Exception e) {

      /*LogDoc
       *
       * @phase local ldap search
       * @reason Failed at setSortKey.
       * @message DBVirtualList: <exception thrown>
       */
      mLogger.log(
          ILogger.EV_SYSTEM,
          ILogger.S_DB,
          ILogger.LL_FAILURE,
          CMS.getLogMessage("OPERATION_ERROR", e.toString()));
    }
    // Paged results also require a sort control
    if (mKeys != null) {
      mPageControls[0] = new LDAPSortControl(mKeys, true);
    } else {
      throw new EBaseException("sort keys cannot be null");
    }
  }
Example #7
0
 /**
  * Constructs a virtual list. Be sure to setPageSize() later if your pageSize is not the default
  * 10 Be sure to setSortKey() before fetchs
  *
  * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
  * version 3 and upper param base the base distinguished name to search from param filter search
  * filter specifying the search criteria param attrs list of attributes that you want returned in
  * the search results
  */
 public DBVirtualList(
     IDBRegistry registry, LDAPConnection c, String base, String filter, String attrs[])
     throws EBaseException {
   mRegistry = registry;
   mFilter = filter;
   mBase = base;
   mAttrs = attrs;
   CMS.debug(
       "In DBVirtualList filter attrs filter: " + filter + " attrs: " + Arrays.toString(attrs));
   mPageControls = new LDAPControl[2];
   try {
     mConn = (LDAPConnection) c.clone();
   } catch (Exception e) {
     throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
   }
 }
Example #8
0
  private synchronized boolean getJumpToPage() {
    try {
      // Get the actual entries
      if (!getEntries()) return false;

      // Check if we have a control returned
      LDAPControl[] c = mConn.getResponseControls();
      LDAPVirtualListResponse nextCont = null;

      if (c != null) {
        for (LDAPControl control : c) {
          if (control instanceof LDAPVirtualListResponse) {
            nextCont = (LDAPVirtualListResponse) control;
            break;
          }
        }
      }

      if (nextCont != null) {
        mSelectedIndex = nextCont.getFirstPosition() - 1;
        mTop = Math.max(0, mSelectedIndex - mBeforeCount);

        CMS.debug("DBVirtualList: top: " + mTop);
        if (mJumpTo != null) {
          mJumpToInitialIndex = mTop;
        }

        // Now we know the total size of the virtual list box
        mSize = nextCont.getContentCount();
        ((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize);
        mInitialized = true;
        // System.out.println( "Virtual window: " + mTop +
        //       ".." + (mTop+mEntries.size()-1) +
        //      " of " + mSize );
      } else {
        mLogger.log(
            ILogger.EV_SYSTEM,
            ILogger.S_DB,
            ILogger.LL_FAILURE,
            CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
      }
      return true;
    } catch (Exception e) {
      // happens when connection is not available
      return false;
    }
  }
Example #9
0
  private String remove_from_ldap(String dn) {
    CMS.debug("UpdateDomainXML: delete_from_ldap: starting dn: " + dn);
    String status = SUCCESS;
    ILdapConnFactory connFactory = null;
    LDAPConnection conn = null;
    IConfigStore cs = CMS.getConfigStore();

    try {
      IConfigStore ldapConfig = cs.getSubStore("internaldb");
      connFactory = CMS.getLdapBoundConnFactory("UpdateDomainXML");
      connFactory.init(ldapConfig);
      conn = connFactory.getConn();
      conn.delete(dn);
    } catch (LDAPException e) {
      int resultCode = e.getLDAPResultCode();
      if (resultCode != LDAPException.NO_SUCH_OBJECT) {
        status = FAILED;
        CMS.debug("Failed to delete entry" + e.toString());
      }
    } catch (Exception e) {
      CMS.debug("Failed to delete entry" + e.toString());
    } finally {
      try {
        if ((conn != null) && (connFactory != null)) {
          CMS.debug("Releasing ldap connection");
          connFactory.returnConn(conn);
        }
      } catch (Exception e) {
        CMS.debug("Error releasing the ldap connection" + e.toString());
      }
    }
    return status;
  }
Example #10
0
  /**
   * Retrieves the size of this virtual list. Recommend to call getSize() before getElementAt() or
   * getElements() since you'd better check if the index is out of bound first.
   */
  public int getSize() {

    CMS.debug("DBVirtualList.getSize()");

    if (!mInitialized) {

      mInitialized = true;
      // Do an initial search to get the virtual list size
      // Keep one page before and one page after the start
      if (mJumpTo == null) {
        mBeforeCount = 0; // mPageSize;
        mAfterCount = mPageSize; //  mPageSize + mPageSize;
      }
      // Create the initial paged results control
      /* Since this one is only used to get the size of the virtual list;
      we don't care about the starting index. If there is no partial
      match, the first one before (or after, if none before) is returned
      as the index entry. Instead of "A", you could use the other
      constructor and specify 0 both for startIndex and for
      contentCount. */
      LDAPVirtualListControl cont = null;

      if (mJumpTo == null) {
        CMS.debug("DBVirtualList: searching for entry A");
        cont = new LDAPVirtualListControl("A", mBeforeCount, mAfterCount);

      } else {
        CMS.debug("DBVirtualList: searching for entry " + mJumpTo);

        if (mPageSize < 0) {
          mBeforeCount = mPageSize * -1;
          mAfterCount = 0;
        }
        cont = new LDAPVirtualListControl(mJumpTo, mBeforeCount, mAfterCount);
      }

      mPageControls[1] = cont;
      getJumpToPage();
    }

    CMS.debug("DBVirtualList: size: " + mSize);
    return mSize;
  }
Example #11
0
  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String startFrom,
      String sortKey,
      int pageSize)
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs startFrom sortKey pageSize "
            + "filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs)
            + " pageSize "
            + pageSize
            + " startFrom "
            + startFrom);
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    mJumpTo = startFrom;
    setSortKey(sortKey);
    // setPageSize(pageSize);

    if (pageSize < 0) {
      mJumpToDirection = -1;
    }
    mPageSize = pageSize;

    mBeforeCount = 0;
    mAfterCount = mPageSize;
  }
Example #12
0
 public boolean isPanelDone() {
   IConfigStore cs = CMS.getConfigStore();
   try {
     String s = cs.getString("preop.cainfo.select", "");
     if (s != null && !s.isEmpty()) {
       return true;
     }
   } catch (EBaseException e) {
   }
   return false;
 }
Example #13
0
  public void update(HttpServletRequest request, HttpServletResponse response, Context context)
      throws IOException {
    IConfigStore config = CMS.getConfigStore();
    String subsystemNick;
    try {
      subsystemNick = config.getString("preop.cert.subsystem.nickname");
    } catch (EBaseException e1) {
      e1.printStackTrace();
      throw new IOException("Failed to get subsystem certificate nickname");
    }

    String url = HttpInput.getString(request, "urls");
    URI caUri = null;
    String parsedURI = url.substring(url.lastIndexOf("http"));
    try {
      caUri = new URI(parsedURI);
    } catch (URISyntaxException e) {
      throw new IOException("Invalid URI " + parsedURI);
    }

    // TODO: get installer from session
    TPSInstaller installer = new TPSInstaller();
    installer.configureCAConnector(caUri, subsystemNick);

    String host = caUri.getHost();
    int port = caUri.getPort();

    // Note -
    // list contains EE port. If admin port is different, it needs to
    // be obtained from security domain and used to get the cert chain

    /* int admin_port = ConfigurationUtils.getPortFromSecurityDomain(domainXML,
            host, port, "CA", "SecurePort", "SecureAdminPort");
    */

    try {
      ConfigurationUtils.importCertChain(host, port, "/ca/admin/ca/getCertChain", "ca");
    } catch (CertificateException
        | SAXException
        | ParserConfigurationException
        | NotInitializedException
        | TokenException
        | EBaseException e) {
      e.printStackTrace();
      throw new IOException("Failed to import certificate chain from CA");
    }

    context.put("updateStatus", "success");
  }
Example #14
0
  private String add_to_ldap(LDAPEntry entry, String dn) {
    CMS.debug("UpdateDomainXML: add_to_ldap: starting");
    String status = SUCCESS;
    ILdapConnFactory connFactory = null;
    LDAPConnection conn = null;
    IConfigStore cs = CMS.getConfigStore();

    try {
      IConfigStore ldapConfig = cs.getSubStore("internaldb");
      connFactory = CMS.getLdapBoundConnFactory("UpdateDomainXML");
      connFactory.init(ldapConfig);
      conn = connFactory.getConn();
      conn.add(entry);
    } catch (LDAPException e) {
      if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
        CMS.debug("UpdateDomainXML: Entry already exists");
        try {
          conn.delete(dn);
          conn.add(entry);
        } catch (LDAPException ee) {
          CMS.debug("UpdateDomainXML: Error when replacing existing entry " + ee.toString());
          status = FAILED;
        }
      } else {
        CMS.debug("UpdateDomainXML: Failed to update ldap domain info. Exception: " + e.toString());
        status = FAILED;
      }
    } catch (Exception e) {
      CMS.debug("Failed to add entry" + e.toString());
    } finally {
      try {
        if ((conn != null) && (connFactory != null)) {
          CMS.debug("Releasing ldap connection");
          connFactory.returnConn(conn);
        }
      } catch (Exception e) {
        CMS.debug("Error releasing the ldap connection" + e.toString());
      }
    }
    return status;
  }
Example #15
0
  /**
   * Get a page starting at "first" (although we may also fetch some preceding entries) Recommend to
   * call getSize() before getElementAt() or getElements() since you'd better check if the index is
   * out of bound first.
   *
   * @param first the index of the first entry of the page you want to fetch
   */
  public boolean getPage(int first) {

    CMS.debug("DBVirtualList.getPage(" + first + ")");

    if (!mInitialized) {
      LDAPVirtualListControl cont = new LDAPVirtualListControl(0, mBeforeCount, mAfterCount, 0);

      mPageControls[1] = cont;
    }

    // CMS.debug("about to set range first " + first + " mBeforeCount " + mBeforeCount + "
    // mAfterCount " + mAfterCount);
    ((LDAPVirtualListControl) mPageControls[1]).setRange(first, mBeforeCount, mAfterCount);
    return getPage();
  }
Example #16
0
  /** Fetch a buffer */
  private boolean getPage() {
    // Get the actual entries
    if (!getEntries()) return false;

    // Check if we have a control returned
    LDAPControl[] c = mConn.getResponseControls();
    LDAPVirtualListResponse nextCont = null;

    if (c != null) {
      for (LDAPControl control : c) {
        if (control instanceof LDAPVirtualListResponse) {
          nextCont = (LDAPVirtualListResponse) control;
          break;
        }
      }
    }

    if (nextCont != null) {
      mSelectedIndex = nextCont.getFirstPosition() - 1;
      mTop = Math.max(0, mSelectedIndex - mBeforeCount);
      // CMS.debug("New mTop: " + mTop + " mSelectedIndex " + mSelectedIndex);
      // Now we know the total size of the virtual list box
      mSize = nextCont.getContentCount();
      ((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize);
      mInitialized = true;
      // System.out.println( "Virtual window: " + mTop +
      //       ".." + (mTop+mEntries.size()-1) +
      //      " of " + mSize );
    } else {

      /*LogDoc
       *
       * @phase local ldap search
       */
      mLogger.log(
          ILogger.EV_SYSTEM,
          ILogger.S_DB,
          ILogger.LL_FAILURE,
          CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
    }
    return true;
  }
  public ExtendedKeyUsageExtension createExtension() {
    ExtendedKeyUsageExtension ext = null;

    try {
      ext = new ExtendedKeyUsageExtension();
    } catch (Exception e) {
      CMS.debug("ExtendedKeyUsageExtDefault: createExtension " + e.toString());
    }
    if (ext == null) return null;
    boolean critical = getBoolean(getConfig(CONFIG_CRITICAL));

    ext.setCritical(critical);
    StringTokenizer st = new StringTokenizer(getConfig(CONFIG_OIDS), ",");

    while (st.hasMoreTokens()) {
      String oid = st.nextToken();

      ext.addOID(new ObjectIdentifier(oid));
    }
    return ext;
  }
Example #18
0
  public void display(HttpServletRequest request, HttpServletResponse response, Context context) {
    String errorString = "";
    context.put("title", "CA Information");
    context.put("panel", "admin/console/config/cainfopanel.vm");
    IConfigStore config = CMS.getConfigStore();

    if (isPanelDone()) {
      // TODO - put the selected URL in selection box.
      // String s = config.getString("preop.cainfo.select");
    }

    // get CA URLs
    Vector<String> v;
    try {
      v = null;
      v = ConfigurationUtils.getUrlListFromSecurityDomain(config, "CA", "SecurePort");
      if (v == null) {
        errorString =
            "No CA found.  CA, TKS and optionally DRM "
                + " must be installed prior to TPS installation";
        context.put("errorString", errorString);
        context.put("preop.cainfo.errorString", errorString);
        return;
      }

      config.putString("preop.ca.list", StringUtils.join(v, ","));
      config.commit(false);
    } catch (EBaseException | IOException | SAXException | ParserConfigurationException e) {
      e.printStackTrace();
      errorString = "Failed to get CA information from security domain. " + e;
      context.put("errorString", errorString);
      context.put("preop.cainfo.errorString", errorString);
      return;
    }

    context.put("urls", v);
    context.put("urls_size", v.size());
    context.put("errorString", "");
    context.put("preop.cainfo.errorString", "");
  }
Example #19
0
  /**
   * Process the HTTP request.
   *
   * <ul>
   *   <li>http.param recoveryID ID of request to recover
   * </ul>
   *
   * @param cmsReq the object holding the request and response information
   */
  public void process(CMSRequest cmsReq) throws EBaseException {

    HttpServletRequest req = cmsReq.getHttpReq();
    HttpServletResponse resp = cmsReq.getHttpResp();
    String auditMessage = null;
    String recoveryID = null;
    String agent = null;

    IAuthToken authToken = authenticate(cmsReq);

    AuthzToken authzToken = null;

    try {
      authzToken = authorize(mAclMethod, authToken, mAuthzResourceName, "download");
    } catch (EAuthzAccessDenied e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
    } catch (Exception e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
    }

    if (authzToken == null) {
      cmsReq.setStatus(ICMSRequest.UNAUTHORIZED);
      return;
    }

    CMSTemplate form = null;
    Locale[] locale = new Locale[1];

    try {
      form = getTemplate(mFormPath, req, locale);
    } catch (IOException e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
      throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
    }

    cmsReq.setStatus(ICMSRequest.SUCCESS);
    IArgBlock header = CMS.createArgBlock();
    IArgBlock fixed = CMS.createArgBlock();
    CMSTemplateParams argSet = new CMSTemplateParams(header, fixed);

    // get status and populate argSet
    try {
      recoveryID = req.getParameter("recoveryID");

      header.addStringValue("recoveryID", recoveryID);

      Hashtable<String, Object> params = mService.getRecoveryParams(recoveryID);

      if (params == null) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_RECOVERY_TOKEN_FOUND_1", recoveryID));
        throw new ECMSGWException(CMS.getUserMessage("CMS_GW_NO_RECOVERY_TOKEN_FOUND", recoveryID));
      }

      // only the init DRM agent can get the pkcs12
      SessionContext sContext = SessionContext.getContext();
      if (sContext != null) {
        agent = (String) sContext.get(SessionContext.USER_ID);
      }

      if (agent == null) {
        CMS.debug("GetPk12::process() - agent is null!");
        throw new EBaseException("agent is null");
      }

      String initAgent = (String) params.get("agent");

      if (!agent.equals(initAgent)) {
        log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_INVALID_AGENT_3", recoveryID, initAgent));

        throw new ECMSGWException(
            CMS.getUserMessage("CMS_GW_INVALID_AGENT", agent, initAgent, recoveryID));
      }

      header.addStringValue("serialNumber", (String) params.get("keyID"));

      // got all approval, return pk12
      byte pkcs12[] = ((IKeyRecoveryAuthority) mService).getPk12(recoveryID);

      if (pkcs12 != null) {
        mService.destroyRecoveryParams(recoveryID);
        try {
          resp.setContentType("application/x-pkcs12");
          resp.getOutputStream().write(pkcs12);
          mRenderResult = false;

          auditMessage =
              CMS.getLogMessage(
                  LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_SUCCESS,
                  agent,
                  ILogger.SUCCESS,
                  recoveryID,
                  "");

          audit(auditMessage);

          return;
        } catch (IOException e) {
          header.addStringValue(
              OUT_ERROR, CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
        }
      } else if (((IKeyRecoveryAuthority) mService).getError(recoveryID) != null) {
        // error in recovery process
        header.addStringValue(OUT_ERROR, ((IKeyRecoveryAuthority) mService).getError(recoveryID));
      } else {
        // pk12 hasn't been created yet. Shouldn't get here
      }
    } catch (EBaseException e) {
      header.addStringValue(OUT_ERROR, e.toString(locale[0]));
    }

    if ((agent != null) && (recoveryID != null)) {
      auditMessage =
          CMS.getLogMessage(
              LOGGING_SIGNED_AUDIT_PRIVATE_KEY_EXPORT_REQUEST_PROCESSED_FAILURE,
              agent,
              ILogger.FAILURE,
              recoveryID,
              "");

      audit(auditMessage);
    }

    try {
      ServletOutputStream out = resp.getOutputStream();

      resp.setContentType("text/html");
      form.renderOutput(out, argSet);
    } catch (IOException e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
      throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
    }

    cmsReq.setStatus(ICMSRequest.SUCCESS);
  }
Example #20
0
 public void cleanUp() throws IOException {
   IConfigStore cs = CMS.getConfigStore();
   cs.putString("preop.cainfo.select", "");
 }
Example #21
0
  /**
   * Process the HTTP request.
   *
   * <ul>
   *   <li>http.param op 'downloadBIN' - return the binary certificate chain
   *   <li>http.param op 'displayIND' - display pretty-print of certificate chain components
   * </ul>
   *
   * @param cmsReq the object holding the request and response information
   */
  protected void process(CMSRequest cmsReq) throws EBaseException {
    CMS.debug("UpdateDomainXML: processing...");
    String status = SUCCESS;
    String status2 = SUCCESS;

    HttpServletRequest httpReq = cmsReq.getHttpReq();
    HttpServletResponse httpResp = cmsReq.getHttpResp();

    CMS.debug("UpdateDomainXML process: authentication starts");
    IAuthToken authToken = null;
    try {
      authToken = authenticate(cmsReq);
    } catch (Exception e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
      outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated", null);
      return;
    }
    if (authToken == null) {
      CMS.debug("UpdateDomainXML process: authToken is null");
      outputError(httpResp, AUTH_FAILURE, "Error: not authenticated", null);
      return;
    }
    CMS.debug("UpdateDomainXML process: authentication done");

    AuthzToken authzToken = null;

    try {
      authzToken = authorize(mAclMethod, authToken, mAuthzResourceName, "modify");
    } catch (EAuthzAccessDenied e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
      outputError(httpResp, "Error: Not authorized");
      return;
    } catch (Exception e) {
      log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
      outputError(httpResp, "Error: Encountered problem during authorization.");
      return;
    }
    if (authzToken == null) {
      CMS.debug("UpdateDomainXML process: authorization error");
      outputError(httpResp, "Error: Not authorized");
      return;
    }

    String list = httpReq.getParameter("list");
    String type = httpReq.getParameter("type");
    String host = httpReq.getParameter("host");
    String name = httpReq.getParameter("name");
    String sport = httpReq.getParameter("sport");
    String agentsport = httpReq.getParameter("agentsport");
    String adminsport = httpReq.getParameter("adminsport");
    String eecaport = httpReq.getParameter("eeclientauthsport");
    String httpport = httpReq.getParameter("httpport");
    String domainmgr = httpReq.getParameter("dm");
    String clone = httpReq.getParameter("clone");
    String operation = httpReq.getParameter("operation");

    // ensure required parameters are present
    // especially important for DS syntax checking
    String missing = "";
    if ((host == null) || host.equals("")) {
      missing += " host ";
    }
    if ((name == null) || name.equals("")) {
      missing += " name ";
    }
    if ((sport == null) || sport.equals("")) {
      missing += " sport ";
    }
    if ((type == null) || type.equals("")) {
      missing += " type ";
    }
    if ((clone == null) || clone.equals("")) {
      clone = "false";
    }

    if (!missing.equals("")) {
      CMS.debug(
          "UpdateDomainXML process: required parameters:" + missing + "not provided in request");
      outputError(httpResp, "Error: required parameters: " + missing + "not provided in request");
      return;
    }

    String auditMessage = null;
    String auditSubjectID = auditSubjectID();
    String auditParams =
        "host;;"
            + host
            + "+name;;"
            + name
            + "+sport;;"
            + sport
            + "+clone;;"
            + clone
            + "+type;;"
            + type;
    if (operation != null) {
      auditParams += "+operation;;" + operation;
    } else {
      auditParams += "+operation;;add";
    }

    String basedn = null;
    String secstore = null;

    IConfigStore cs = CMS.getConfigStore();

    try {
      basedn = cs.getString("internaldb.basedn");
      secstore = cs.getString("securitydomain.store");
    } catch (Exception e) {
      CMS.debug(
          "Unable to determine security domain name or basedn. Please run the domaininfo migration script");
    }

    if ((basedn != null) && (secstore != null) && (secstore.equals("ldap"))) {
      // update in ldap

      LDAPEntry entry = null;
      String listName = type + "List";
      String cn = host + ":";

      if ((adminsport != null) && (adminsport != "")) {
        cn += adminsport;
      } else {
        cn += sport;
      }

      String dn = "cn=" + cn + ",cn=" + listName + ",ou=Security Domain," + basedn;
      CMS.debug("UpdateDomainXML: updating LDAP entry: " + dn);

      LDAPAttributeSet attrs = null;
      attrs = new LDAPAttributeSet();
      attrs.add(new LDAPAttribute("objectclass", "top"));
      attrs.add(new LDAPAttribute("objectclass", "pkiSubsystem"));
      attrs.add(new LDAPAttribute("cn", cn));
      attrs.add(new LDAPAttribute("Host", host));
      attrs.add(new LDAPAttribute("SecurePort", sport));

      if ((agentsport != null) && (!agentsport.equals(""))) {
        attrs.add(new LDAPAttribute("SecureAgentPort", agentsport));
      }
      if ((adminsport != null) && (!adminsport.equals(""))) {
        attrs.add(new LDAPAttribute("SecureAdminPort", adminsport));
      }
      if ((httpport != null) && (!httpport.equals(""))) {
        attrs.add(new LDAPAttribute("UnSecurePort", httpport));
      }
      if ((eecaport != null) && (!eecaport.equals(""))) {
        attrs.add(new LDAPAttribute("SecureEEClientAuthPort", eecaport));
      }
      if ((domainmgr != null) && (!domainmgr.equals(""))) {
        attrs.add(new LDAPAttribute("DomainManager", domainmgr.toUpperCase()));
      }
      attrs.add(new LDAPAttribute("clone", clone.toUpperCase()));
      attrs.add(new LDAPAttribute("SubsystemName", name));
      entry = new LDAPEntry(dn, attrs);

      if ((operation != null) && (operation.equals("remove"))) {
        status = remove_from_ldap(dn);
        String adminUserDN;
        if ((agentsport != null) && (!agentsport.equals(""))) {
          adminUserDN = "uid=" + type + "-" + host + "-" + agentsport + ",ou=People," + basedn;
        } else {
          adminUserDN = "uid=" + type + "-" + host + "-" + sport + ",ou=People," + basedn;
        }
        String userAuditParams =
            "Scope;;users+Operation;;OP_DELETE+source;;UpdateDomainXML"
                + "+resource;;"
                + adminUserDN;
        if (status.equals(SUCCESS)) {
          // remove the user for this subsystem's admin
          status2 = remove_from_ldap(adminUserDN);
          if (status2.equals(SUCCESS)) {
            auditMessage =
                CMS.getLogMessage(
                    LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
                    auditSubjectID,
                    ILogger.SUCCESS,
                    userAuditParams);
            audit(auditMessage);

            // remove this user from the subsystem group
            userAuditParams =
                "Scope;;groups+Operation;;OP_DELETE_USER"
                    + "+source;;UpdateDomainXML"
                    + "+resource;;Subsystem Group+user;;"
                    + adminUserDN;
            dn = "cn=Subsystem Group, ou=groups," + basedn;
            LDAPModification mod =
                new LDAPModification(
                    LDAPModification.DELETE, new LDAPAttribute("uniqueMember", adminUserDN));
            status2 = modify_ldap(dn, mod);
            if (status2.equals(SUCCESS)) {
              auditMessage =
                  CMS.getLogMessage(
                      LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
                      auditSubjectID,
                      ILogger.SUCCESS,
                      userAuditParams);
            } else {
              auditMessage =
                  CMS.getLogMessage(
                      LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
                      auditSubjectID,
                      ILogger.FAILURE,
                      userAuditParams);
            }
            audit(auditMessage);
          } else { // error deleting user
            auditMessage =
                CMS.getLogMessage(
                    LOGGING_SIGNED_AUDIT_CONFIG_ROLE,
                    auditSubjectID,
                    ILogger.FAILURE,
                    userAuditParams);
            audit(auditMessage);
          }
        }
      } else {
        status = add_to_ldap(entry, dn);
      }
    } else {
      // update the domain.xml file
      String path = CMS.getConfigStore().getString("instanceRoot", "") + "/conf/domain.xml";

      CMS.debug("UpdateDomainXML: got path=" + path);

      try {
        // using domain.xml file
        CMS.debug("UpdateDomainXML: Inserting new domain info");
        XMLObject parser = new XMLObject(new FileInputStream(path));
        Node n = parser.getContainer(list);
        int count = 0;

        if ((operation != null) && (operation.equals("remove"))) {
          // delete node
          Document doc = parser.getDocument();
          NodeList nodeList = doc.getElementsByTagName(type);
          int len = nodeList.getLength();

          for (int i = 0; i < len; i++) {
            Node nn = nodeList.item(i);
            Vector<String> v_name = parser.getValuesFromContainer(nn, "SubsystemName");
            Vector<String> v_host = parser.getValuesFromContainer(nn, "Host");
            Vector<String> v_adminport = parser.getValuesFromContainer(nn, "SecureAdminPort");
            if ((v_name.elementAt(0).equals(name))
                && (v_host.elementAt(0).equals(host))
                && (v_adminport.elementAt(0).equals(adminsport))) {
              Node parent = nn.getParentNode();
              parent.removeChild(nn);
              count--;
              break;
            }
          }
        } else {
          // add node
          Node parent = parser.createContainer(n, type);
          parser.addItemToContainer(parent, "SubsystemName", name);
          parser.addItemToContainer(parent, "Host", host);
          parser.addItemToContainer(parent, "SecurePort", sport);
          parser.addItemToContainer(parent, "SecureAgentPort", agentsport);
          parser.addItemToContainer(parent, "SecureAdminPort", adminsport);
          parser.addItemToContainer(parent, "SecureEEClientAuthPort", eecaport);
          parser.addItemToContainer(parent, "UnSecurePort", httpport);
          parser.addItemToContainer(parent, "DomainManager", domainmgr.toUpperCase());
          parser.addItemToContainer(parent, "Clone", clone.toUpperCase());
          count++;
        }
        // update count

        String countS = "";
        NodeList nlist = n.getChildNodes();
        Node countnode = null;
        for (int i = 0; i < nlist.getLength(); i++) {
          Element nn = (Element) nlist.item(i);
          String tagname = nn.getTagName();
          if (tagname.equals("SubsystemCount")) {
            countnode = nn;
            NodeList nlist1 = nn.getChildNodes();
            Node nn1 = nlist1.item(0);
            countS = nn1.getNodeValue();
            break;
          }
        }

        CMS.debug("UpdateDomainXML process: SubsystemCount=" + countS);
        try {
          count += Integer.parseInt(countS);
        } catch (Exception ee) {
        }

        n.removeChild(countnode);
        parser.addItemToContainer(n, "SubsystemCount", "" + count);

        // recreate domain.xml
        CMS.debug("UpdateDomainXML: Recreating domain.xml");
        byte[] b = parser.toByteArray();
        FileOutputStream fos = new FileOutputStream(path);
        fos.write(b);
        fos.close();
      } catch (Exception e) {
        CMS.debug("Failed to update domain.xml file" + e.toString());
        status = FAILED;
      }
    }

    if (status.equals(SUCCESS)) {
      auditMessage =
          CMS.getLogMessage(
              LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE,
              auditSubjectID,
              ILogger.SUCCESS,
              auditParams);
    } else {
      // what if already exists or already deleted
      auditMessage =
          CMS.getLogMessage(
              LOGGING_SIGNED_AUDIT_SECURITY_DOMAIN_UPDATE,
              auditSubjectID,
              ILogger.FAILURE,
              auditParams);
    }
    audit(auditMessage);

    if (status.equals(SUCCESS) && status2.equals(SUCCESS)) {
      status = SUCCESS;
    } else {
      status = FAILED;
    }

    try {
      // send success status back to the requestor
      CMS.debug("UpdateDomainXML: Sending response");
      XMLObject xmlObj = new XMLObject();
      Node root = xmlObj.createRoot("XMLResponse");

      xmlObj.addItemToContainer(root, "Status", status);
      byte[] cb = xmlObj.toByteArray();

      outputResult(httpResp, "application/xml", cb);
    } catch (Exception e) {
      CMS.debug("UpdateDomainXML: Failed to send the XML output" + e.toString());
    }
  }
  public String getText(Locale locale) {
    String params[] = {getConfig(CONFIG_CRITICAL), getConfig(CONFIG_OIDS)};

    return CMS.getUserMessage(locale, "CMS_PROFILE_DEF_EXTENDED_KEY_EXT", params);
  }
Example #23
0
/**
 * A class represents a virtual list of search results. Note that this class must be used with
 * DS4.0.
 *
 * @author thomask
 * @author mzhao
 * @version $Revision$, $Date$
 */
public class DBVirtualList<E> implements IDBVirtualList<E> {

  private IDBRegistry mRegistry = null;
  private LDAPConnection mConn = null;
  private String mBase = null;
  private String mFilter = null;
  private String mAttrs[] = null;
  // virtual list size
  private int mSize = -1;

  private Vector<E> mEntries = new Vector<E>();
  // mSize is get or not?
  private boolean mInitialized = false;
  private LDAPSortKey[] mKeys;
  private LDAPControl[] mPageControls = null;
  // page buffer size
  private int mPageSize = 10;
  // the top of the buffer
  private int mTop = 0;
  private int mBeforeCount;
  private int mAfterCount;
  // the index of the first entry returned
  private int mSelectedIndex = 0;
  private int mJumpToIndex = 0;
  private int mJumpToInitialIndex = 0; // Initial index hit in jumpto operation
  private int mJumpToDirection = 1; // Do we proceed forward or backwards
  private String mJumpTo = null; // Determines if this is the jumpto case

  private ILogger mLogger = CMS.getLogger();

  /**
   * Constructs a virtual list. Be sure to setPageSize() later if your pageSize is not the default
   * 10 Be sure to setSortKey() before fetchs
   *
   * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
   * version 3 and upper param base the base distinguished name to search from param filter search
   * filter specifying the search criteria param attrs list of attributes that you want returned in
   * the search results
   */
  public DBVirtualList(
      IDBRegistry registry, LDAPConnection c, String base, String filter, String attrs[])
      throws EBaseException {
    mRegistry = registry;
    mFilter = filter;
    mBase = base;
    mAttrs = attrs;
    CMS.debug(
        "In DBVirtualList filter attrs filter: " + filter + " attrs: " + Arrays.toString(attrs));
    mPageControls = new LDAPControl[2];
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
  }

  /**
   * Constructs a virtual list. Be sure to setPageSize() later if your pageSize is not the default
   * 10
   *
   * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
   * version 3 and upper param base the base distinguished name to search from param filter search
   * filter specifying the search criteria param attrs list of attributes that you want returned in
   * the search results param sortKey the attributes to sort by
   */
  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String sortKey[])
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs sotrKey[]  filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs));
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    setSortKey(sortKey);
  }

  /**
   * Constructs a virtual list. Be sure to setPageSize() later if your pageSize is not the default
   * 10
   *
   * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
   * version 3 and upper param base the base distinguished name to search from param filter search
   * filter specifying the search criteria param attrs list of attributes that you want returned in
   * the search results param sortKey the attribute to sort by
   */
  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String sortKey)
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs sortKey   filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs));
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    setSortKey(sortKey);
  }

  /**
   * Constructs a virtual list.
   *
   * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
   * version 3 and upper param base the base distinguished name to search from param filter search
   * filter specifying the search criteria param attrs list of attributes that you want returned in
   * the search results param sortKey the attributes to sort by param pageSize the size of a page.
   * There is a 3*pageSize buffer maintained so pageUp and pageDown won't invoke fetch from ldap
   * server
   */
  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String sortKey[],
      int pageSize)
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs sortKey[] pageSize filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs)
            + " pageSize "
            + pageSize);
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    setSortKey(sortKey);
    setPageSize(pageSize);
  }

  /**
   * Constructs a virtual list.
   *
   * <p>param registry the registry of attribute mappers param c the ldap connection. It has to be
   * version 3 and upper param base the base distinguished name to search from param filter search
   * filter specifying the search criteria param attrs list of attributes that you want returned in
   * the search results param sortKey the attribute to sort by param pageSize the size of a page.
   * There is a 3*pageSize buffer maintained so pageUp and pageDown won't invoke fetch from ldap
   * server
   */
  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String sortKey,
      int pageSize)
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs sortKey pageSize filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs)
            + " pageSize "
            + pageSize);
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    setSortKey(sortKey);
    setPageSize(pageSize);
  }

  public DBVirtualList(
      IDBRegistry registry,
      LDAPConnection c,
      String base,
      String filter,
      String attrs[],
      String startFrom,
      String sortKey,
      int pageSize)
      throws EBaseException {

    CMS.debug(
        "In DBVirtualList filter attrs startFrom sortKey pageSize "
            + "filter: "
            + filter
            + " attrs: "
            + Arrays.toString(attrs)
            + " pageSize "
            + pageSize
            + " startFrom "
            + startFrom);
    mRegistry = registry;
    mFilter = filter;
    try {
      mConn = (LDAPConnection) c.clone();
    } catch (Exception e) {
      throw new EBaseException(CMS.getUserMessage("CMS_BASE_CONN_FAILED", e.toString()));
    }
    mBase = base;
    mAttrs = attrs;
    mPageControls = new LDAPControl[2];
    mJumpTo = startFrom;
    setSortKey(sortKey);
    // setPageSize(pageSize);

    if (pageSize < 0) {
      mJumpToDirection = -1;
    }
    mPageSize = pageSize;

    mBeforeCount = 0;
    mAfterCount = mPageSize;
  }

  /**
   * Set the paging size of this virtual list. The page size here is just a buffer size. A buffer is
   * kept around that is three times as large as the number of visible entries. That way, you can
   * scroll up/down several items(up to a page-full) without refetching entries from the directory.
   *
   * @param size the page size
   */
  public void setPageSize(int size) {

    if (mJumpTo != null) {
      return;
    }

    mPageSize = size;
    mBeforeCount = 0; // mPageSize;
    mAfterCount = mPageSize; // mPageSize + mPageSize;

    // CMS.debug("In setPageSize " + size + " mBeforeCount " + mBeforeCount + " mAfterCount " +
    // mAfterCount);
  }

  /**
   * set the sort key
   *
   * @param sortKey the attribute to sort by
   */
  public void setSortKey(String sortKey) throws EBaseException {
    String keys[] = new String[1];

    keys[0] = sortKey;
    setSortKey(keys);
  }

  /**
   * set the sort key
   *
   * @param sortKey the attributes to sort by
   */
  public void setSortKey(String[] sortKeys) throws EBaseException {
    if (sortKeys == null) throw new EBaseException("sort keys cannot be null");
    try {
      mKeys = new LDAPSortKey[sortKeys.length];
      String la[] = null;
      synchronized (this) {
        la = mRegistry.getLDAPAttributes(sortKeys);
      }

      for (int j = 0; j < sortKeys.length; j++) {
        mKeys[j] = new LDAPSortKey(la[j]);
      }
    } catch (Exception e) {

      /*LogDoc
       *
       * @phase local ldap search
       * @reason Failed at setSortKey.
       * @message DBVirtualList: <exception thrown>
       */
      mLogger.log(
          ILogger.EV_SYSTEM,
          ILogger.S_DB,
          ILogger.LL_FAILURE,
          CMS.getLogMessage("OPERATION_ERROR", e.toString()));
    }
    // Paged results also require a sort control
    if (mKeys != null) {
      mPageControls[0] = new LDAPSortControl(mKeys, true);
    } else {
      throw new EBaseException("sort keys cannot be null");
    }
  }

  /**
   * Retrieves the size of this virtual list. Recommend to call getSize() before getElementAt() or
   * getElements() since you'd better check if the index is out of bound first.
   */
  public int getSize() {

    CMS.debug("DBVirtualList.getSize()");

    if (!mInitialized) {

      mInitialized = true;
      // Do an initial search to get the virtual list size
      // Keep one page before and one page after the start
      if (mJumpTo == null) {
        mBeforeCount = 0; // mPageSize;
        mAfterCount = mPageSize; //  mPageSize + mPageSize;
      }
      // Create the initial paged results control
      /* Since this one is only used to get the size of the virtual list;
      we don't care about the starting index. If there is no partial
      match, the first one before (or after, if none before) is returned
      as the index entry. Instead of "A", you could use the other
      constructor and specify 0 both for startIndex and for
      contentCount. */
      LDAPVirtualListControl cont = null;

      if (mJumpTo == null) {
        CMS.debug("DBVirtualList: searching for entry A");
        cont = new LDAPVirtualListControl("A", mBeforeCount, mAfterCount);

      } else {
        CMS.debug("DBVirtualList: searching for entry " + mJumpTo);

        if (mPageSize < 0) {
          mBeforeCount = mPageSize * -1;
          mAfterCount = 0;
        }
        cont = new LDAPVirtualListControl(mJumpTo, mBeforeCount, mAfterCount);
      }

      mPageControls[1] = cont;
      getJumpToPage();
    }

    CMS.debug("DBVirtualList: size: " + mSize);
    return mSize;
  }

  public int getSizeBeforeJumpTo() {

    if (!mInitialized || mJumpTo == null) return 0;

    int size = 0;

    if (mJumpToDirection < 0) {
      size = mTop + mEntries.size();
    } else {
      size = mTop;
    }

    return size;
  }

  public int getSizeAfterJumpTo() {

    if (!mInitialized || mJumpTo == null) return 0;

    int size = mSize - mTop;

    return size;
  }

  private synchronized boolean getEntries() {

    CMS.debug("DBVirtualList.getEntries()");

    // Specify necessary controls for vlist
    // LDAPSearchConstraints cons = mConn.getSearchConstraints();
    LDAPSearchConstraints cons = new LDAPSearchConstraints();

    cons.setMaxResults(0);
    if (mPageControls != null) {
      cons.setServerControls(mPageControls);
      // System.out.println( "setting vlist control" );
    }
    // Empty the buffer
    mEntries.removeAllElements();
    // Do a search
    try {
      // what happen if there is no matching?
      String ldapFilter = mRegistry.getFilter(mFilter);
      String ldapAttrs[] = null;
      LDAPSearchResults result;

      if (mAttrs != null) {
        ldapAttrs = mRegistry.getLDAPAttributes(mAttrs);

        /*
        LDAPv2.SCOPE_BASE:
        (search only the base DN)
        LDAPv2.SCOPE_ONE:
        (search only entries under the base DN)
        LDAPv2.SCOPE_SUB:
        (search the base DN and all entries within its subtree)
        */
        result = mConn.search(mBase, LDAPConnection.SCOPE_ONE, ldapFilter, ldapAttrs, false, cons);

      } else {
        result = mConn.search(mBase, LDAPConnection.SCOPE_ONE, ldapFilter, null, false, cons);
      }
      if (result == null) {
        return false;
      }
      int damageCounter = 0;

      while (result.hasMoreElements()) {
        LDAPEntry entry = (LDAPEntry) result.nextElement();

        try {
          // maintain mEntries as vector of LDAPEntry
          @SuppressWarnings("unchecked")
          E o = (E) mRegistry.createObject(entry.getAttributeSet());

          mEntries.addElement(o);
        } catch (Exception e) {

          CMS.debug("Exception " + e);

          /*LogDoc
           *
           * @phase local ldap search
           * @reason Failed to get enties.
           * @message DBVirtualList: <exception thrown>
           */
          mLogger.log(
              ILogger.EV_SYSTEM,
              ILogger.S_DB,
              ILogger.LL_FAILURE,
              CMS.getLogMessage("CMSCORE_DBS_VL_ADD", e.toString()));
          // #539044
          damageCounter++;
          if (damageCounter > 100) {
            mLogger.log(
                ILogger.EV_SYSTEM,
                ILogger.S_DB,
                ILogger.LL_FAILURE,
                CMS.getLogMessage(
                    "CMSCORE_DBS_VL_CORRUPTED_ENTRIES", Integer.toString(damageCounter)));
            return false;
          }
        }
      }
    } catch (Exception e) {

      /*LogDoc
       *
       * @phase local ldap search
       * @reason Failed to get enties.
       * @message DBVirtualList: <exception thrown>
       */
      CMS.debug("getEntries: exception " + e);

      mLogger.log(
          ILogger.EV_SYSTEM,
          ILogger.S_DB,
          ILogger.LL_FAILURE,
          CMS.getLogMessage("OPERATION_ERROR", e.toString()));
    }
    // System.out.println( "Returning " + mEntries.size() +
    //       " entries" );

    CMS.debug("DBVirtualList: entries: " + mEntries.size());

    return true;
  }

  public int getCurrentIndex() {
    return mTop;
  }

  private synchronized boolean getJumpToPage() {
    try {
      // Get the actual entries
      if (!getEntries()) return false;

      // Check if we have a control returned
      LDAPControl[] c = mConn.getResponseControls();
      LDAPVirtualListResponse nextCont = null;

      if (c != null) {
        for (LDAPControl control : c) {
          if (control instanceof LDAPVirtualListResponse) {
            nextCont = (LDAPVirtualListResponse) control;
            break;
          }
        }
      }

      if (nextCont != null) {
        mSelectedIndex = nextCont.getFirstPosition() - 1;
        mTop = Math.max(0, mSelectedIndex - mBeforeCount);

        CMS.debug("DBVirtualList: top: " + mTop);
        if (mJumpTo != null) {
          mJumpToInitialIndex = mTop;
        }

        // Now we know the total size of the virtual list box
        mSize = nextCont.getContentCount();
        ((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize);
        mInitialized = true;
        // System.out.println( "Virtual window: " + mTop +
        //       ".." + (mTop+mEntries.size()-1) +
        //      " of " + mSize );
      } else {
        mLogger.log(
            ILogger.EV_SYSTEM,
            ILogger.S_DB,
            ILogger.LL_FAILURE,
            CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
      }
      return true;
    } catch (Exception e) {
      // happens when connection is not available
      return false;
    }
  }

  /**
   * Get a page starting at "first" (although we may also fetch some preceding entries) Recommend to
   * call getSize() before getElementAt() or getElements() since you'd better check if the index is
   * out of bound first.
   *
   * @param first the index of the first entry of the page you want to fetch
   */
  public boolean getPage(int first) {

    CMS.debug("DBVirtualList.getPage(" + first + ")");

    if (!mInitialized) {
      LDAPVirtualListControl cont = new LDAPVirtualListControl(0, mBeforeCount, mAfterCount, 0);

      mPageControls[1] = cont;
    }

    // CMS.debug("about to set range first " + first + " mBeforeCount " + mBeforeCount + "
    // mAfterCount " + mAfterCount);
    ((LDAPVirtualListControl) mPageControls[1]).setRange(first, mBeforeCount, mAfterCount);
    return getPage();
  }

  /** Fetch a buffer */
  private boolean getPage() {
    // Get the actual entries
    if (!getEntries()) return false;

    // Check if we have a control returned
    LDAPControl[] c = mConn.getResponseControls();
    LDAPVirtualListResponse nextCont = null;

    if (c != null) {
      for (LDAPControl control : c) {
        if (control instanceof LDAPVirtualListResponse) {
          nextCont = (LDAPVirtualListResponse) control;
          break;
        }
      }
    }

    if (nextCont != null) {
      mSelectedIndex = nextCont.getFirstPosition() - 1;
      mTop = Math.max(0, mSelectedIndex - mBeforeCount);
      // CMS.debug("New mTop: " + mTop + " mSelectedIndex " + mSelectedIndex);
      // Now we know the total size of the virtual list box
      mSize = nextCont.getContentCount();
      ((LDAPVirtualListControl) mPageControls[1]).setListSize(mSize);
      mInitialized = true;
      // System.out.println( "Virtual window: " + mTop +
      //       ".." + (mTop+mEntries.size()-1) +
      //      " of " + mSize );
    } else {

      /*LogDoc
       *
       * @phase local ldap search
       */
      mLogger.log(
          ILogger.EV_SYSTEM,
          ILogger.S_DB,
          ILogger.LL_FAILURE,
          CMS.getLogMessage("CMSCORE_DBS_VL_NULL_RESPONSE"));
    }
    return true;
  }

  /**
   * Called by application to scroll the list with initial letters. Consider text to be an initial
   * substring of the attribute of the primary sorting key(the first one specified in the sort key
   * array) of an entry. If no entries match, the one just before(or after, if none before) will be
   * returned as mSelectedIndex
   *
   * @param text the prefix of the first entry of the page you want to fetch
   */
  public boolean getPage(String text) {
    mPageControls[1] = new LDAPVirtualListControl(text, mBeforeCount, mAfterCount);
    // System.out.println( "Setting requested start to " +
    //      text + ", -" + mBeforeCount + ", +" +
    //      mAfterCount );
    return getPage();
  }

  /**
   * fetch data of a single list item Recommend to call getSize() before getElementAt() or
   * getElements() since you'd better check if the index is out of bound first. If the index is out
   * of range of the virtual list, an exception will be thrown and return null
   *
   * @param index the index of the element to fetch
   */
  public E getElementAt(int index) {

    /* mSize may not be init at this time! Bad !
     * the caller should really check the index is within bound before this
     * but I'll take care of this just in case they are too irresponsible
     */
    if (!mInitialized) {
      mSize = getSize();
    }

    CMS.debug("DBVirtualList: retrieving entry #" + index);

    // System.out.println( "need entry " + index );
    if ((index < 0) || (index >= mSize)) {
      CMS.debug("DBVirtualList: returning null");
      return null;
    }

    if (mJumpTo != null) { // Handle the explicit jumpto case

      if (index == 0) mJumpToIndex = 0; // Keep a running jumpto index for this page of data
      else mJumpToIndex++;

      // CMS.debug("getElementAtJT: " + index  +  " mTop " + mTop + " mEntries.size() " +
      // mEntries.size());

      if ((mJumpToDirection > 0)
          && (mJumpToInitialIndex + index >= mSize)) // out of data in forward paging jumpto case
      {
        CMS.debug("mJumpTo virtual list exhausted   mTop " + mTop + " mSize " + mSize);
        return null;
      }

      if (mJumpToIndex >= mEntries.size()) // In jumpto case, page of data has been exhausted
      {
        mJumpToIndex = 0; // new page will be needed reset running count

        if (mJumpToDirection > 0) { // proceed in positive direction past hit point
          getPage(index + mJumpToInitialIndex + 1);
        } else { // proceed backwards from hit point
          if (mTop == 0) {
            getPage(0);
            CMS.debug("asking for a page less than zero in reverse case, return null");
            return null;
          }

          CMS.debug("getting page reverse mJumptoIndex  " + mJumpToIndex + " mTop " + mTop);
          getPage(mTop);
        }
      }

      if (mJumpToDirection > 0) // handle getting entry in forward direction
      {
        return mEntries.elementAt(mJumpToIndex);
      } else { // handle getting entry in reverse direction
        int reverse_index = mEntries.size() - mJumpToIndex - 1;

        CMS.debug("reverse direction getting index " + reverse_index);

        if (reverse_index < 0 || reverse_index >= mEntries.size()) {
          CMS.debug("reverse_index out of range " + reverse_index);
          return null;
        }
        return mEntries.elementAt(reverse_index);
      }
    }

    // CMS.debug("getElementAt noJumpto: " + index);

    if ((index < mTop) || (index >= mTop + mEntries.size())) { // handle the non jumpto case
      // fetch a new page
      // System.out.println( "fetching a page starting at " +
      //        index );
      //   CMS.debug("getElementAt noJumpto: getting page index: " + index + " mEntries.size() " +
      // mEntries.size() + " mTop: " + mTop);
      getPage(index);
    }

    int offset = index - mTop;

    if ((offset < 0) || (offset >= mEntries.size()))
      // XXX
      return null; // ("No entry at " + index);
    else return mEntries.elementAt(offset);
  }

  public E getJumpToElementAt(int i) {
    return mEntries.elementAt(i);
  }

  /** This function processes elements as soon as it arrives. It is more memory-efficient. */
  public void processElements(int startidx, int endidx, IElementProcessor ep)
      throws EBaseException {

    /* mSize may not be init at this time! Bad !
     * the caller should really check the index is within bound before this
     * but I'll take care of this just in case they are too irresponsible
     */
    if (!mInitialized) mSize = getSize();

    // short-cut the existing code ... :(
    if (mJumpTo != null) {
      for (int i = startidx; i <= endidx; i++) {
        Object element = getJumpToElementAt(i);

        if (element != null) ep.process(element);
      }
      return;
    }

    // guess this is what you really mean to try to improve performance
    if (startidx >= endidx) {
      throw new EBaseException("startidx must be less than endidx");
    } else {
      setPageSize(endidx - startidx);
      getPage(startidx);
    }

    for (int i = startidx; i <= endidx; i++) {
      Object element = getElementAt(i);

      if (element != null) ep.process(element);
    }
  }

  /** get the virutal selected index */
  public int getSelectedIndex() {
    return mSelectedIndex;
  }

  /** get the top of the buffer */
  public int getFirstIndex() {
    return mTop;
  }
}
Example #24
0
  /**
   * fetch data of a single list item Recommend to call getSize() before getElementAt() or
   * getElements() since you'd better check if the index is out of bound first. If the index is out
   * of range of the virtual list, an exception will be thrown and return null
   *
   * @param index the index of the element to fetch
   */
  public E getElementAt(int index) {

    /* mSize may not be init at this time! Bad !
     * the caller should really check the index is within bound before this
     * but I'll take care of this just in case they are too irresponsible
     */
    if (!mInitialized) {
      mSize = getSize();
    }

    CMS.debug("DBVirtualList: retrieving entry #" + index);

    // System.out.println( "need entry " + index );
    if ((index < 0) || (index >= mSize)) {
      CMS.debug("DBVirtualList: returning null");
      return null;
    }

    if (mJumpTo != null) { // Handle the explicit jumpto case

      if (index == 0) mJumpToIndex = 0; // Keep a running jumpto index for this page of data
      else mJumpToIndex++;

      // CMS.debug("getElementAtJT: " + index  +  " mTop " + mTop + " mEntries.size() " +
      // mEntries.size());

      if ((mJumpToDirection > 0)
          && (mJumpToInitialIndex + index >= mSize)) // out of data in forward paging jumpto case
      {
        CMS.debug("mJumpTo virtual list exhausted   mTop " + mTop + " mSize " + mSize);
        return null;
      }

      if (mJumpToIndex >= mEntries.size()) // In jumpto case, page of data has been exhausted
      {
        mJumpToIndex = 0; // new page will be needed reset running count

        if (mJumpToDirection > 0) { // proceed in positive direction past hit point
          getPage(index + mJumpToInitialIndex + 1);
        } else { // proceed backwards from hit point
          if (mTop == 0) {
            getPage(0);
            CMS.debug("asking for a page less than zero in reverse case, return null");
            return null;
          }

          CMS.debug("getting page reverse mJumptoIndex  " + mJumpToIndex + " mTop " + mTop);
          getPage(mTop);
        }
      }

      if (mJumpToDirection > 0) // handle getting entry in forward direction
      {
        return mEntries.elementAt(mJumpToIndex);
      } else { // handle getting entry in reverse direction
        int reverse_index = mEntries.size() - mJumpToIndex - 1;

        CMS.debug("reverse direction getting index " + reverse_index);

        if (reverse_index < 0 || reverse_index >= mEntries.size()) {
          CMS.debug("reverse_index out of range " + reverse_index);
          return null;
        }
        return mEntries.elementAt(reverse_index);
      }
    }

    // CMS.debug("getElementAt noJumpto: " + index);

    if ((index < mTop) || (index >= mTop + mEntries.size())) { // handle the non jumpto case
      // fetch a new page
      // System.out.println( "fetching a page starting at " +
      //        index );
      //   CMS.debug("getElementAt noJumpto: getting page index: " + index + " mEntries.size() " +
      // mEntries.size() + " mTop: " + mTop);
      getPage(index);
    }

    int offset = index - mTop;

    if ((offset < 0) || (offset >= mEntries.size()))
      // XXX
      return null; // ("No entry at " + index);
    else return mEntries.elementAt(offset);
  }
Example #25
0
 /**
  * initialize the servlet.
  *
  * @param sc servlet configuration, read from the web.xml file
  */
 public void init(ServletConfig sc) throws ServletException {
   CMS.debug("UpdateDomainXML: initializing...");
   super.init(sc);
   CMS.debug("UpdateDomainXML: done initializing...");
 }
Example #26
0
  private synchronized boolean getEntries() {

    CMS.debug("DBVirtualList.getEntries()");

    // Specify necessary controls for vlist
    // LDAPSearchConstraints cons = mConn.getSearchConstraints();
    LDAPSearchConstraints cons = new LDAPSearchConstraints();

    cons.setMaxResults(0);
    if (mPageControls != null) {
      cons.setServerControls(mPageControls);
      // System.out.println( "setting vlist control" );
    }
    // Empty the buffer
    mEntries.removeAllElements();
    // Do a search
    try {
      // what happen if there is no matching?
      String ldapFilter = mRegistry.getFilter(mFilter);
      String ldapAttrs[] = null;
      LDAPSearchResults result;

      if (mAttrs != null) {
        ldapAttrs = mRegistry.getLDAPAttributes(mAttrs);

        /*
        LDAPv2.SCOPE_BASE:
        (search only the base DN)
        LDAPv2.SCOPE_ONE:
        (search only entries under the base DN)
        LDAPv2.SCOPE_SUB:
        (search the base DN and all entries within its subtree)
        */
        result = mConn.search(mBase, LDAPConnection.SCOPE_ONE, ldapFilter, ldapAttrs, false, cons);

      } else {
        result = mConn.search(mBase, LDAPConnection.SCOPE_ONE, ldapFilter, null, false, cons);
      }
      if (result == null) {
        return false;
      }
      int damageCounter = 0;

      while (result.hasMoreElements()) {
        LDAPEntry entry = (LDAPEntry) result.nextElement();

        try {
          // maintain mEntries as vector of LDAPEntry
          @SuppressWarnings("unchecked")
          E o = (E) mRegistry.createObject(entry.getAttributeSet());

          mEntries.addElement(o);
        } catch (Exception e) {

          CMS.debug("Exception " + e);

          /*LogDoc
           *
           * @phase local ldap search
           * @reason Failed to get enties.
           * @message DBVirtualList: <exception thrown>
           */
          mLogger.log(
              ILogger.EV_SYSTEM,
              ILogger.S_DB,
              ILogger.LL_FAILURE,
              CMS.getLogMessage("CMSCORE_DBS_VL_ADD", e.toString()));
          // #539044
          damageCounter++;
          if (damageCounter > 100) {
            mLogger.log(
                ILogger.EV_SYSTEM,
                ILogger.S_DB,
                ILogger.LL_FAILURE,
                CMS.getLogMessage(
                    "CMSCORE_DBS_VL_CORRUPTED_ENTRIES", Integer.toString(damageCounter)));
            return false;
          }
        }
      }
    } catch (Exception e) {

      /*LogDoc
       *
       * @phase local ldap search
       * @reason Failed to get enties.
       * @message DBVirtualList: <exception thrown>
       */
      CMS.debug("getEntries: exception " + e);

      mLogger.log(
          ILogger.EV_SYSTEM,
          ILogger.S_DB,
          ILogger.LL_FAILURE,
          CMS.getLogMessage("OPERATION_ERROR", e.toString()));
    }
    // System.out.println( "Returning " + mEntries.size() +
    //       " entries" );

    CMS.debug("DBVirtualList: entries: " + mEntries.size());

    return true;
  }
Example #27
0
  /**
   * Implements ISubsystem.startup
   *
   * <p>
   *
   * @see ISubsystem#startup
   */
  public void startup() throws EBaseException {
    mLogger = CMS.getLogger();

    mLogger.log(
        ILogger.EV_SYSTEM, ILogger.S_REQQUEUE, ILogger.LL_INFO, "Request subsystem started");
  }
Example #28
0
  public CAApplication() {

    // account
    classes.add(AccountService.class);

    // installer
    classes.add(CAInstallerService.class);

    // sub-ca management
    classes.add(AuthorityService.class);

    // certs and requests
    classes.add(CertService.class);
    classes.add(CertRequestService.class);

    // profile management
    classes.add(ProfileService.class);

    // selftests
    classes.add(SelfTestService.class);

    // user and group management
    classes.add(GroupService.class);
    classes.add(UserService.class);

    // system certs
    classes.add(SystemCertService.class);

    // kra connector
    classes.add(KRAConnectorService.class);

    // features
    classes.add(FeatureService.class);

    // security domain
    IConfigStore cs = CMS.getConfigStore();

    // check server state
    int state;
    try {
      state = cs.getInteger("cs.state");
    } catch (EBaseException e) {
      CMS.debug(e);
      throw new RuntimeException(e);
    }

    // if server is configured, check security domain selection
    if (state == 1) {
      String select;
      try {
        select = cs.getString("securitydomain.select");
      } catch (EBaseException e) {
        CMS.debug(e);
        throw new RuntimeException(e);
      }

      // if it's a new security domain, register the service
      if ("new".equals(select)) {
        classes.add(SecurityDomainService.class);
      }
    }

    // exception mapper
    classes.add(PKIExceptionMapper.class);

    // interceptors
    singletons.add(new SessionContextInterceptor());
    singletons.add(new AuthMethodInterceptor());
    singletons.add(new ACLInterceptor());
    singletons.add(new MessageFormatInterceptor());
  }