/*
 * This function uses the date specified by "matchDate" to set up the
 * CrlSelector for a Date match. It is intended to test the case where there
 * is no "smart" database query, so the CertStore should throw an error
 * rather than ask the database for all available CRLs and then filter the
 * results using the selector.
 */
static void
testMatchCrlDate(
    char *dateMatch,
    char *expectedAscii,
    void *plContext)
{
    PKIX_PL_Date *dateCriterion = NULL;
    PKIX_CertStore *crlStore = NULL;
    PKIX_CRLSelector *crlSelector = NULL;
    PKIX_List *crlList = NULL;
    PKIX_CertStore_CRLCallback getCrl = NULL;

    PKIX_TEST_STD_VARS();

    subTest("Searching CRLs for matching Date");

    dateCriterion = createDate(dateMatch, plContext);
    test_makeDateCRLSelector(dateCriterion, &crlSelector, plContext);

    PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Pk11CertStore_Create(&crlStore, plContext));

    PKIX_TEST_EXPECT_NO_ERROR(PKIX_CertStore_GetCRLCallback(crlStore, &getCrl, plContext));

    PKIX_TEST_EXPECT_ERROR(getCrl(crlStore, crlSelector, NULL, &crlList, plContext));

cleanup:

    PKIX_TEST_DECREF_AC(dateCriterion);
    PKIX_TEST_DECREF_AC(crlStore);
    PKIX_TEST_DECREF_AC(crlSelector);
    PKIX_TEST_DECREF_AC(crlList);

    PKIX_TEST_RETURN();
}
/*
 * This function reads a directory-file crl specified by "desiredIssuerCrl",
 * and decodes the IssuerName. It uses that name to set up the CrlSelector
 * for a Issuer Name match, and then queries the database for matching entries.
 * It is intended to test the case of a "smart" database query.
 */
static 
void testMatchCrlIssuer(
        char *crlDir,
        char *desiredIssuerCrl,
        char *expectedAscii,
        void *plContext)
{
        PKIX_UInt32 numCrl = 0;
        PKIX_PL_CRL *crlWithDesiredIssuer = NULL;
        PKIX_CertStore *crlStore = NULL;
        PKIX_CRLSelector *crlSelector = NULL;
        PKIX_List *crlList = NULL;
        PKIX_CertStore_CRLCallback getCrl = NULL;
	void *nbioContext = NULL;

        PKIX_TEST_STD_VARS();

        subTest("Searching CRLs for matching Issuer");

        crlWithDesiredIssuer = createCRL(crlDir, desiredIssuerCrl, plContext);

        test_makeIssuerCRLSelector
                (crlWithDesiredIssuer, &crlSelector, plContext);

        PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Pk11CertStore_Create
                (&crlStore, plContext));

        PKIX_TEST_EXPECT_NO_ERROR(PKIX_CertStore_GetCRLCallback
                (crlStore, &getCrl, plContext));

        PKIX_TEST_EXPECT_NO_ERROR(getCrl
                (crlStore,
		crlSelector,
                &nbioContext,
		&crlList,
		plContext));

        PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetLength
                (crlList, &numCrl, plContext));

        if (numCrl > 0) {
                /* List should be immutable */
                PKIX_TEST_EXPECT_ERROR(PKIX_List_DeleteItem
                (crlList, 0, plContext));
        }

        if (expectedAscii) {
                testToStringHelper
                        ((PKIX_PL_Object *)crlList, expectedAscii, plContext);
        }

cleanup:

        PKIX_TEST_DECREF_AC(crlWithDesiredIssuer);
        PKIX_TEST_DECREF_AC(crlStore);
        PKIX_TEST_DECREF_AC(crlSelector);
        PKIX_TEST_DECREF_AC(crlList);

        PKIX_TEST_RETURN();
}
static void
testGetCRL(char *crlDir)
{
    PKIX_PL_String *dirString = NULL;
    PKIX_CertStore_CRLCallback crlCallback;
    PKIX_CertStore *certStore = NULL;
    PKIX_CRLSelector *crlSelector = NULL;
    PKIX_List *crlList = NULL;
    PKIX_UInt32 numCrl = 0;
    void *nbioContext = NULL;

    PKIX_TEST_STD_VARS();

    PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_String_Create(PKIX_ESCASCII,
                                                    crlDir,
                                                    0,
                                                    &dirString,
                                                    plContext));

    subTest("PKIX_PL_CollectionCertStore_Create");
    PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CollectionCertStore_Create(dirString,
                                                                 &certStore,
                                                                 plContext));

    subTest("PKIX_CRLSelector_Create");
    PKIX_TEST_EXPECT_NO_ERROR(PKIX_CRLSelector_Create(testCRLSelectorMatchCallback,
                                                      NULL,
                                                      &crlSelector,
                                                      plContext));

    subTest("PKIX_CertStore_GetCRLCallback");
    PKIX_TEST_EXPECT_NO_ERROR(PKIX_CertStore_GetCRLCallback(certStore, &crlCallback, NULL));

    subTest("Getting data from CRL Callback");
    PKIX_TEST_EXPECT_NO_ERROR(crlCallback(certStore,
                                          crlSelector,
                                          &nbioContext,
                                          &crlList,
                                          plContext));

    PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetLength(crlList,
                                                  &numCrl,
                                                  plContext));

    if (numCrl != PKIX_TEST_COLLECTIONCERTSTORE_NUM_CRLS) {
        pkixTestErrorMsg = "unexpected CRL number mismatch";
    }

cleanup:

    PKIX_TEST_DECREF_AC(dirString);
    PKIX_TEST_DECREF_AC(crlList);
    PKIX_TEST_DECREF_AC(crlSelector);
    PKIX_TEST_DECREF_AC(certStore);

    PKIX_TEST_RETURN();
}
/*
 * FUNCTION: pkix_CrlChecker_CheckRemote
 *
 * DESCRIPTION:
 *  Check if the Cert has been revoked based the CRLs data.  This function
 *  maintains the checker state to be current.
 *
 * PARAMETERS
 *  "checker"
 *      Address of CertChainChecker which has the state data.
 *      Must be non-NULL.
 *  "cert"
 *      Address of Certificate that is to be validated. Must be non-NULL.
 *  "unreslvdCrtExts"
 *      A List OIDs. Not **yet** used in this checker function.
 *  "plContext"
 *      Platform-specific context pointer.
 *
 * THREAD SAFETY:
 *  Not Thread Safe
 *      (see Thread Safety Definitions in Programmer's Guide)
 *
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a CertChainChecker Error if the function fails in a non-fatal way.
 *  Returns a Fatal Error
 */
PKIX_Error *
pkix_CrlChecker_CheckExternal(
        PKIX_PL_Cert *cert,
        PKIX_PL_Cert *issuer,
        PKIX_PL_Date *date,
        pkix_RevocationMethod *checkerObject,
        PKIX_ProcessingParams *procParams,
        PKIX_UInt32 methodFlags,
        PKIX_RevocationStatus *pRevStatus,
        PKIX_UInt32 *pReasonCode,
        void **pNBIOContext,
        void *plContext)
{
    PKIX_CertStore_CheckRevokationByCrlCallback storeCheckRevocationFn = NULL;
    PKIX_CertStore_ImportCrlCallback storeImportCrlFn = NULL;
    PKIX_RevocationStatus revStatus = PKIX_RevStatus_NoInfo;
    PKIX_CertStore *certStore = NULL;
    PKIX_CertStore *localStore = NULL;
    PKIX_CRLSelector *crlSelector = NULL;
    PKIX_PL_X500Name *issuerName = NULL;
    pkix_CrlChecker *state = NULL; 
    PKIX_UInt32 reasonCode = 0;
    PKIX_UInt32 crlStoreIndex = 0;
    PKIX_UInt32 numCrlStores = 0;
    PKIX_Boolean storeIsLocal = PKIX_FALSE;
    PKIX_List *crlList = NULL;
    PKIX_List *dpList = NULL;
    void *nbioContext = NULL;

    PKIX_ENTER(CERTCHAINCHECKER, "pkix_CrlChecker_CheckExternal");
    PKIX_NULLCHECK_FOUR(cert, issuer, checkerObject, pNBIOContext);
    
    nbioContext = *pNBIOContext;
    *pNBIOContext = NULL; /* prepare for Error exit */

    state = (pkix_CrlChecker*)checkerObject;
    
    PKIX_CHECK(
        PKIX_List_GetLength(state->certStores, &numCrlStores, plContext),
        PKIX_LISTGETLENGTHFAILED);

    /* Find a cert store that is capable of storing crls */
    for (;crlStoreIndex < numCrlStores;crlStoreIndex++) {
        PKIX_CHECK(
            PKIX_List_GetItem(state->certStores, crlStoreIndex,
                              (PKIX_PL_Object **)&certStore,
                              plContext),
            PKIX_LISTGETITEMFAILED);
        
        PKIX_CHECK(
            PKIX_CertStore_GetLocalFlag(certStore, &storeIsLocal,
                                        plContext),
            PKIX_CERTSTOREGETLOCALFLAGFAILED);
        if (storeIsLocal) {
            PKIX_CHECK(
                PKIX_CertStore_GetImportCrlCallback(certStore,
                                                    &storeImportCrlFn,
                                                    plContext),
                PKIX_CERTSTOREGETCHECKREVBYCRLFAILED);
            
            PKIX_CHECK(
                PKIX_CertStore_GetCrlCheckerFn(certStore,
                                               &storeCheckRevocationFn,
                                               plContext),
                PKIX_CERTSTOREGETCHECKREVBYCRLFAILED);
            
            if (storeImportCrlFn && storeCheckRevocationFn) {
                localStore = certStore;
                certStore = NULL;
                break;
            }
        }
        PKIX_DECREF(certStore);
    } /* while */

    /* Report unknown status if we can not check crl in one of the
     * local stores. */
    if (!localStore) {
        PKIX_ERROR_FATAL(PKIX_CRLCHECKERNOLOCALCERTSTOREFOUND);
    }
    PKIX_CHECK(
        PKIX_PL_Cert_VerifyKeyUsage(issuer, PKIX_CRL_SIGN, plContext),
        PKIX_CERTCHECKKEYUSAGEFAILED);
    PKIX_CHECK(
        PKIX_PL_Cert_GetCrlDp(cert, &dpList, plContext),
        PKIX_CERTGETCRLDPFAILED);
    if (!(methodFlags & PKIX_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE) &&
        (!dpList || !dpList->length)) {
        goto cleanup;
    }
    PKIX_CHECK(
        PKIX_PL_Cert_GetIssuer(cert, &issuerName, plContext),
        PKIX_CERTGETISSUERFAILED);
    PKIX_CHECK(
        PKIX_CRLSelector_Create(issuer, dpList, date, &crlSelector, plContext),
        PKIX_CRLCHECKERSETSELECTORFAILED);
    /* Fetch crl and store in a local cert store */
    for (crlStoreIndex = 0;crlStoreIndex < numCrlStores;crlStoreIndex++) {
        PKIX_CertStore_CRLCallback getCrlsFn;

        PKIX_CHECK(
            PKIX_List_GetItem(state->certStores, crlStoreIndex,
                              (PKIX_PL_Object **)&certStore,
                              plContext),
            PKIX_LISTGETITEMFAILED);
        
        PKIX_CHECK(
            PKIX_CertStore_GetCRLCallback(certStore, &getCrlsFn,
                                          plContext),
            PKIX_CERTSTOREGETCRLCALLBACKFAILED);
        
        PKIX_CHECK(
            (*getCrlsFn)(certStore, crlSelector, &nbioContext,
                      &crlList, plContext),
            PKIX_GETCRLSFAILED);

        PKIX_CHECK(
            (*storeImportCrlFn)(localStore, issuerName, crlList, plContext),
            PKIX_CERTSTOREFAILTOIMPORTCRLLIST);
        
        PKIX_CHECK(
            (*storeCheckRevocationFn)(certStore, cert, issuer, date,
                                      /* done with crl downloading */
                                      PKIX_TRUE,
                                      &reasonCode, &revStatus, plContext),
            PKIX_CERTSTORECRLCHECKFAILED);
        if (revStatus != PKIX_RevStatus_NoInfo) {
            break;
        }
        PKIX_DECREF(crlList);
        PKIX_DECREF(certStore);
    } /* while */

cleanup:
    /* Update return flags */
    if (revStatus == PKIX_RevStatus_NoInfo && 
	((dpList && dpList->length > 0) ||
	 (methodFlags & PKIX_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE)) &&
        methodFlags & PKIX_REV_M_FAIL_ON_MISSING_FRESH_INFO) {
        revStatus = PKIX_RevStatus_Revoked;
    }
    *pRevStatus = revStatus;

    PKIX_DECREF(dpList);
    PKIX_DECREF(crlList);
    PKIX_DECREF(certStore);
    PKIX_DECREF(issuerName);
    PKIX_DECREF(localStore);
    PKIX_DECREF(crlSelector);

    PKIX_RETURN(CERTCHAINCHECKER);
}
/*
 * FUNCTION: pkix_DefaultCRLChecker_Check_Store
 *
 * DESCRIPTION:
 *  Checks the certStore pointed to by "certStore" for a CRL that may determine
 *  whether the Cert pointed to by "cert" has been revoked.
 *
 * PARAMETERS
 *  "checker"
 *      Address of CertChainChecker which has the state data.
 *      Must be non-NULL.
 *  "cert"
 *      Address of Certificate that is to be validated. Must be non-NULL.
 *  "prevPublicKey"
 *      Address of previous public key in the backward chain. May be NULL.
 *  "state"
 *      Address of DefaultCrlCheckerState. Must be non-NULL.
 *  "unresolvedCriticalExtensions"
 *      A List OIDs. Not **yet** used in this checker function.
 *  "certStore"
 *      Address of the CertStore to be queried for a relevant CRL. Must be
 *      non-NULL.
 *  "pNBIOContext"
 *      Address at which platform-dependent information is stored if processing
 *      is suspended for non-blocking I/O. Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 *
 * THREAD SAFETY:
 *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
 *
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a DefaultCrlCheckerState Error if the function fails in a
 *  non-fatal way.
 *  Returns a Fatal Error
 */
static PKIX_Error *
pkix_DefaultCRLChecker_Check_Store(
        PKIX_CertChainChecker *checker,
        PKIX_PL_Cert *cert,
        PKIX_PL_PublicKey *prevPublicKey,
        pkix_DefaultCRLCheckerState *state,
        PKIX_List *unresolvedCriticalExtensions,
        PKIX_CertStore *certStore,
        void **pNBIOContext,
        void *plContext)
{

        PKIX_Boolean cacheFlag = PKIX_FALSE;
        PKIX_Boolean cacheHit = PKIX_FALSE;
        PKIX_UInt32 numEntries = 0;
        PKIX_UInt32 i = 0;
        PKIX_Int32 reasonCode = 0;
        PKIX_UInt32 allReasonCodes = 0;
        PKIX_List *crlList = NULL;
        PKIX_List *crlEntryList = NULL;
        PKIX_PL_CRLEntry *crlEntry = NULL;
        PKIX_Error *checkCrlFail = NULL;
        PKIX_CertStore_CRLCallback getCrls = NULL;
        void *nbioContext = NULL;

        PKIX_ENTER(CERTCHAINCHECKER, "pkix_DefaultCRLChecker_Check_Store");
        PKIX_NULLCHECK_TWO(checker, cert);
        PKIX_NULLCHECK_THREE(state, certStore, pNBIOContext);

        nbioContext = *pNBIOContext;
        *pNBIOContext = NULL;

        /* Are this CertStore's entries in cache? */
        PKIX_CHECK(PKIX_CertStore_GetCertStoreCacheFlag
                (certStore, &cacheFlag, plContext),
                PKIX_CERTSTOREGETCERTSTORECACHEFLAGFAILED);

        if (cacheFlag) {

                PKIX_CHECK(pkix_CacheCrlEntry_Lookup
                        (certStore,
                        state->certIssuer,
                        state->certSerialNumber,
                        &cacheHit,
                        &crlEntryList,
                        plContext),
                        PKIX_CACHECRLENTRYLOOKUPFAILED);

        }

        if (cacheHit) {

                /* Use cached data */

                PKIX_CHECK(PKIX_List_GetLength
                        (crlEntryList, &numEntries, plContext),
                        PKIX_LISTGETLENGTHFAILED);

                for (i = 0; i < numEntries; i++) {

                    PKIX_CHECK(PKIX_List_GetItem
                            (crlEntryList,
                            i,
                            (PKIX_PL_Object **)&crlEntry,
                            plContext),
                            PKIX_LISTGETITEMFAILED);

                    PKIX_CHECK(PKIX_PL_CRLEntry_GetCRLEntryReasonCode
                            (crlEntry, &reasonCode, plContext),
                            PKIX_CRLENTRYGETCRLENTRYREASONCODEFAILED);

		    if (reasonCode >= 0) {
			if (reasonCode >= numReasonCodes) 
			    reasonCode = 0;

			allReasonCodes |= (1 << reasonCode);

			PKIX_DEFAULTCRLCHECKERSTATE_DEBUG_ARG
                                    ("CRL revocation Reason: %s\n ",
                                    reasonCodeMsgString[reasonCode]);

                    }

                    PKIX_DECREF(crlEntry);
                }

                state->reasonCodeMask |= allReasonCodes;

                if (allReasonCodes != 0) {

                        PKIX_ERROR(PKIX_CERTIFICATEREVOKEDBYCRL);
                }
 
                PKIX_DECREF(crlEntryList);

       } else {

                if (nbioContext == NULL) {
                        PKIX_CHECK(PKIX_CertStore_GetCRLCallback
                                (certStore, &getCrls, plContext),
                                PKIX_CERTSTOREGETCRLCALLBACKFAILED);

                        PKIX_CHECK(getCrls
                                (certStore,
                                state->crlSelector,
                                &nbioContext,
                                &crlList,
                                plContext),
                                PKIX_GETCRLSFAILED);
                } else {
                        PKIX_CHECK(PKIX_CertStore_CrlContinue
                                (certStore,
                                state->crlSelector,
                                &nbioContext,
                                &crlList,
                                plContext),
                                PKIX_CERTSTORECRLCONTINUEFAILED);
                }

                /*
                 * Verify Certificate validity: if one CertStore provides
                 * reason code, we stop here. Instead of exhausting all
                 * CertStores to get all possible reason codes associated
                 *  with the Cert. May be expanded if desire otherwise.
                 */

                if (crlList == NULL) {

                        *pNBIOContext = nbioContext;
                } else {

                        *pNBIOContext = NULL;

                        checkCrlFail = pkix_DefaultCRLChecker_CheckCRLs
                                (cert,
                                state->certIssuer,
                                state->certSerialNumber,
                                prevPublicKey,
                                crlList,
                                state,
                                &crlEntryList,
                                plContext);

                        if (checkCrlFail) {
                                if (crlEntryList != NULL) {
                                        /* Add to cache */
                                        PKIX_CHECK(pkix_CacheCrlEntry_Add
                                               (certStore,
                                               state->certIssuer,
                                               state->certSerialNumber,
                                               crlEntryList,
                                               plContext),
                                               PKIX_CACHECRLENTRYADDFAILED);
                                }
                                PKIX_ERROR(PKIX_CERTIFICATEREVOKEDBYCRL);
                        }
                }

                PKIX_DECREF(crlList);

        }

cleanup:
        PKIX_DECREF(crlEntryList);
        PKIX_DECREF(crlEntry);
        PKIX_DECREF(crlList);
        PKIX_DECREF(checkCrlFail);

        PKIX_RETURN(CERTCHAINCHECKER);
}