[IOT-789] [IOT-792] [IOT-794] [IOT-1763 partial fix]
authorNathan Heldt-Sheller <nathan.heldt-sheller@intel.com>
Tue, 24 Jan 2017 06:30:50 +0000 (22:30 -0800)
committerRandeep Singh <randeep.s@samsung.com>
Tue, 7 Feb 2017 09:35:51 +0000 (09:35 +0000)
Remove AMS and clean up SRM context and response code.

The AMS code is dead, broken, and needs to be removed.

Also, the SRM uses a tangled and inconsistent set of context objects,
leaving it unclear which request is being processed, what the state
of processing is, and whether or not a response has been sent to the
requester.

This patch fixes this and should be used as the basis
for future improvements to the policy engine (ACL) code,
SVR handling, etc.

There is some additional cleanup I'd like to do, but this needs
to get merged, and is already a large change, so I'll add those
other fixes as smaller patches once this is merged to master.

NOTE TO REVIEWERS: a few places are marked "TODO Samsung" and need
review by Samsung engr because it is a Samsung feature.

patch set 7: deleted commented out code and files

patch set 8: fixed const assignment warning that was causing Arduino
build to fail

patch set 9: rebased and merged 16883

patch set 10: addressed Kevin's comments and automated build issue

patch set 11: automated build issue

patch set 12: automated build issue

Change-Id: I9560c8aeb1ee59925c0b7aa1282f0cf39f3cae9b
Signed-off-by: Nathan Heldt-Sheller <nathan.heldt-sheller@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/16719
Reviewed-by: Kevin Kane <kkane@microsoft.com>
Tested-by: jenkins-iotivity <jenkins@iotivity.org>
Reviewed-by: Randeep Singh <randeep.s@samsung.com>
resource/csdk/security/SConscript
resource/csdk/security/include/internal/amsmgr.h [deleted file]
resource/csdk/security/include/internal/policyengine.h
resource/csdk/security/include/internal/secureresourcemanager.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/src/amsmgr.c [deleted file]
resource/csdk/security/src/policyengine.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/unittest/policyengine.cpp
resource/csdk/stack/src/ocstack.c

index 57746f0..e510931 100644 (file)
@@ -104,7 +104,6 @@ libocsrm_src = [
        OCSRM_SRC + 'aclresource.c',
        OCSRM_SRC + 'verresource.c',
        OCSRM_SRC + 'amaclresource.c',
-       OCSRM_SRC + 'amsmgr.c',
        OCSRM_SRC + 'pstatresource.c',
        OCSRM_SRC + 'doxmresource.c',
        OCSRM_SRC + 'credresource.c',
diff --git a/resource/csdk/security/include/internal/amsmgr.h b/resource/csdk/security/include/internal/amsmgr.h
deleted file mode 100644 (file)
index de5a9cc..0000000
+++ /dev/null
@@ -1,129 +0,0 @@
-//******************************************************************
-//
-// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#ifndef IOTVT_SRM_AMSMGR_H
-#define IOTVT_SRM_AMSMGR_H
-
-#include <stdlib.h>
-#include <stdint.h>
-
-#include "ocstack.h"
-#include "logger.h"
-#include "policyengine.h"
-#include "securevirtualresourcetypes.h"
-#include "cainterface.h"
-
-typedef struct PEContext PEContext_t;
-/**
- * The AMS context.
- */
-typedef struct AmsMgrContext
-{
-    OicUuid_t           amsDeviceId;  /**< DeviceID of the oic.sec.ams service. */
-    CAEndpoint_t        *endpoint;
-    CARequestInfo_t     *requestInfo;
-} AmsMgrContext_t;
-
-/**
- * This method updates AmsMgr context's endpoint & requestInfo.
- *
- * @param context is the policy engine context.
- * @param endpoint is the CA Endpoint info of the requester.
- * @param requestInfo is the CA RequestInfo of the requester.
- *
- * @return ::OC_STACK_OK if successful, else other value in case of error.
- */
-OCStackResult UpdateAmsMgrContext(PEContext_t *context,
-                                  const CAEndpoint_t *endpoint,
-                                  const CARequestInfo_t *requestInfo);
-
-/**
- * This method is called by PolicyEngine to Discover AMS service.
- * It sends muticast discovery request such as
- * /oic/sec/doxm?deviceid="AMSSrvcDeviceID" to discover AMS service
- * with deviceId="AMSSrvcDeviceID".
- *
- * @param context is the policy engine context.
- *
- * @return ::OC_STACK_OK,If able to successfully send multicast discovery request.
- * else ::OC_STACK_ERROR, If unable to successfully send multicast discovery request
- * due to error.
- */
-OCStackResult DiscoverAmsService(PEContext_t *context);
-
-/**
- * This method sends unicast request to retrieve the secured port info of the
- * discovered AMS service. It sends unicast discovery request such as
- * /oic/res?rt="oic.sec.doxm" to the discovered AMS service.
- *
- * @param context is the policy engine context.
- *
- * @return ::OC_STACK_OK,If able to successfully send unicast discovery request.
- * else ::OC_STACK_ERROR, If unable to successfully send unicast discovery request
- * due to error.
- */
-OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,
-                                             OCDevAddr *devAddr,
-                                             OCConnectivityType connType);
-
-/**
- * This method sends unicast request to AMS service to get ACL for
- * the Subject and/or Resource. It sends unicast request such as
- * /oic/sec/acl?sub="subjectId";rsrc="/a/led" to get the ACL for
- * the subject & resource.
- *
- * @param context is the policy engine context.
- *
- * @return ::OC_STACK_OK, If able to successfully send unicast ACL request.
- * ::OC_STACK_ERROR, If unable to successfully send unicast ACL request due to error.
- *
- */
-OCStackResult SendAclReq(PEContext_t *context,
-                         OCDevAddr *devAddr,
-                         OCConnectivityType connType,
-                         uint16_t securedPort);
-
-/*
- * This method is used by Policy engine to checks Amacl resource.
- * If Amacl is found then it fills up context->amsMgrContext->amsDeviceId
- * with amsID of the Amacl else leaves it empty.
- *
- * @param context is the policy engine context.
- *
- * @return true, if Amacl for the resource is found. false, if Amacl for the
- * resource is not found
- */
-bool FoundAmaclForRequest(PEContext_t *context);
-
-/*
- * This method is used by Policy engine to process AMS request.
- *
- * @param context is the policy engine context.
- */
-void ProcessAMSRequest(PEContext_t *context);
-
-/*
- * This method is used by Policy engine to free AMS context requestInfo/
- *
- * @param requestInfo is the pointer to @ref CARequestInfo_t.
- */
-void FreeCARequestInfo(CARequestInfo_t *requestInfo);
-
-#endif //IOTVT_SRM_AMSMGR_H
index 83841c1..5d7c097 100644 (file)
 #include "ocstack.h"
 #include "logger.h"
 #include "securevirtualresourcetypes.h"
+#include "secureresourcemanager.h"
 #include "cainterface.h"
-#include "amsmgr.h"
 #include <stdlib.h>
 #include <stdint.h>
 
-typedef struct AmsMgrContext AmsMgrContext_t;
-
-typedef enum PEState
-{
-    STOPPED = 0,              //Policy engine state machine is not running
-    AWAITING_REQUEST,         //Can process new request
-    AWAITING_AMS_RESPONSE,    //Can't process new request; waiting for AMS response
-    BUSY                      //Can't process new request as processing other requests
-} PEState_t;
-
-typedef struct PEContext
-{
-    PEState_t   state;
-    OicUuid_t   subject;
-    char        resource[MAX_URI_LENGTH];
-    OicSecSvrType_t resourceType;
-    uint16_t    permission;
-    bool        amsProcessing;
-    SRMAccessResponse_t retVal;
-    AmsMgrContext_t     *amsMgrContext;
-
-#ifdef MULTIPLE_OWNER
-    uint8_t* payload;
-    size_t payloadSize;
-#endif //MULTIPLE_OWNER
-} PEContext_t;
-
 /**
  * Check whether a request should be allowed.
  *
- * @param context is the pointer to Policy Engine context to use.
- * @param subjectId is the pointer to Id of the requesting entity.
- * @param resource is the pointer to URI of Resource being requested.
- * @param permission is the requested permission.
- *
- * @return ::ACCESS_GRANTED if request should go through, otherwise some flavor of ACCESS_DENIED.
- */
-SRMAccessResponse_t CheckPermission(
-    PEContext_t     *context,
-    const OicUuid_t *subjectId,
-    const char      *resource,
-    const uint16_t  requestedPermission);
-
-/**
- * Initialize the Policy Engine. Call this before calling CheckPermission().
- * TODO Eventually this and DeInit() need to be called from a new
- *      "SRMInit(SRMContext_t *)" function, TBD after BeachHead.
- * @param context is the pointer to Policy Engine context to initialize.
+ * @param context is the pointer to SRM Request Context to use.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * Upon return, context->responseVal will be set to ACCESS_GRANTED if request
+ * should be processed, otherwise context->responseVal will be set to
+ * some flavor of ACCESS_DENIED.
  */
-OCStackResult InitPolicyEngine(PEContext_t *context);
-
-/**
- * De-Initialize the Policy Engine. Call this before exiting to allow Policy
- * Engine to do cleanup on context.
- *
- * @param context is the pointer to Policy Engine context to de-initialize.
- */
-void DeInitPolicyEngine(PEContext_t *context);
+void CheckPermission( SRMRequestContext_t *context );
 
 /**
  * Get CRUDN permission for a method.
@@ -99,15 +49,6 @@ void DeInitPolicyEngine(PEContext_t *context);
  */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method);
 
-/*
- * This method reset Policy Engine context to default state and update
- * it's state to @param state.
- *
- * @param context is the policy engine context.
- * @param state set Policy engine state to this.
- */
-void SetPolicyEngineState(PEContext_t *context, const PEState_t state);
-
 typedef OCStackResult (*GetSvrRownerId_t)(OicUuid_t *rowner);
 
 #endif //IOTVT_SRM_PE_H
index 7976452..b6d74e2 100644 (file)
 #define SECURITYRESOURCEMANAGER_H_
 
 #include "securevirtualresourcetypes.h"
+#include "cainterface.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+typedef enum SubjectIdentityType
+{
+    SUBJECT_ID_TYPE_ERROR = 0,
+    SUBJECT_ID_TYPE_UUID,     // Subject refers to a UUID
+    SUBJECT_ID_TYPE_ROLE,     // Subject refers to a Role
+} SubjectIdentityType_t;
+
+/**
+ * The context for a single request to be processed by the Security
+ * Resource Manager.
+ */
+typedef struct SRMRequestContext
+{
+    const CAEndpoint_t      *endPoint;                          // ptr to the Endpoint for this request
+    OicSecSvrType_t         resourceType;                       // SVR type (or "not an SVR")
+    char                    resourceUri[MAX_URI_LENGTH + 1];    // URI of the requested resource
+    uint16_t                requestedPermission;                // bitmask permissions of request
+    CAResponseInfo_t        responseInfo;                       // The response for this request
+    bool                    responseSent;                       // Is servicing this request complete?
+    SRMAccessResponse_t     responseVal;                        // The SRM internal response code
+    const CARequestInfo_t   *requestInfo;                       // ptr to info for this request
+    bool                    secureChannel;                      // Was request recv'd over secure channel?
+    bool                    slowResponseSent;                   // Is a full response still needed?
+    SubjectIdentityType_t   subjectIdType;                      // The type of Subject ID in this
+                                                                // request.
+    OicUuid_t               subjectUuid;                        // The UUID of the Subject (valid
+                                                                // iff IdType is UUID_TYPE).
+    // Developer note: when adding support for an additional type (e.g.
+    // ROLE_TYPE) suggest adding a new var to hold the Subject ID for that type.
+#ifdef MULTIPLE_OWNER
+    uint8_t*                payload;
+    size_t                  payloadSize;
+#endif //MULTIPLE_OWNER
+} SRMRequestContext_t;
+
 /**
  * Register Persistent storage callback.
  *
@@ -68,18 +104,6 @@ OCStackResult SRMInitSecureResources();
 void SRMDeInitSecureResources();
 
 /**
- * Initialize Policy Engine context.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
- */
-OCStackResult SRMInitPolicyEngine();
-
-/**
- * Cleanup Policy Engine context.
- */
-void SRMDeInitPolicyEngine();
-
-/**
  * Provisioning API response callback.
  *
  * @param object endpoint instance.
@@ -111,14 +135,6 @@ bool SRMIsSecurityResourceURI(const char* uri);
  */
 OicSecSvrType_t GetSvrTypeFromUri(const char* uri);
 
-/**
- * Sends Response
- * @param   resposeVal       SRMAccessResponse_t value
- * @return  NONE
- */
-void SRMSendResponse(SRMAccessResponse_t responseVal);
-
-
 #ifdef __cplusplus
 }
 #endif
index c6b6756..25d1e19 100644 (file)
@@ -57,20 +57,20 @@ extern "C" {
  * Values used to create bit-maskable enums for single-value response with
  * embedded code.
  */
-#define ACCESS_GRANTED_DEF            (1 << 0)
-#define ACCESS_DENIED_DEF             (1 << 1)
-#define INSUFFICIENT_PERMISSION_DEF   (1 << 2)
-#define SUBJECT_NOT_FOUND_DEF         (1 << 3)
-#define RESOURCE_NOT_FOUND_DEF        (1 << 4)
-#define POLICY_ENGINE_ERROR_DEF       (1 << 5)
-#define INVALID_PERIOD_DEF            (1 << 6)
-#define ACCESS_WAITING_DEF            (1 << 7)
-#define AMS_SERVICE_DEF               (1 << 8)
+#define ACCESS_GRANTED_DEF                      (1 << 0)
+#define ACCESS_DENIED_DEF                       (1 << 1)
+#define INSUFFICIENT_PERMISSION_DEF             (1 << 2)
+#define SUBJECT_NOT_FOUND_DEF                   (1 << 3)
+#define RESOURCE_NOT_FOUND_DEF                  (1 << 4)
+#define POLICY_ENGINE_ERROR_DEF                 (1 << 5)
+#define INVALID_PERIOD_DEF                      (1 << 6)
+#define SEC_RESOURCE_OVER_UNSECURE_CHANNEL_DEF  (1 << 7)
 #define REASON_MASK_DEF               (INSUFFICIENT_PERMISSION_DEF | \
                                        INVALID_PERIOD_DEF | \
                                        SUBJECT_NOT_FOUND_DEF | \
                                        RESOURCE_NOT_FOUND_DEF | \
-                                       POLICY_ENGINE_ERROR_DEF)
+                                       POLICY_ENGINE_ERROR_DEF | \
+                                       SEC_RESOURCE_OVER_UNSECURE_CHANNEL_DEF)
 
 
 /**
@@ -81,6 +81,7 @@ extern "C" {
  * 4th lsb:  D (Delete)
  * 5th lsb:  N (Notify)
  */
+#define PERMISSION_ERROR        (0x0)
 #define PERMISSION_CREATE       (1 << 0)
 #define PERMISSION_READ         (1 << 1)
 #define PERMISSION_WRITE        (1 << 2)
@@ -121,10 +122,8 @@ typedef enum
         | RESOURCE_NOT_FOUND_DEF,
     ACCESS_DENIED_POLICY_ENGINE_ERROR = ACCESS_DENIED_DEF
         | POLICY_ENGINE_ERROR_DEF,
-    ACCESS_WAITING_FOR_AMS = ACCESS_WAITING_DEF
-        | AMS_SERVICE_DEF,
-    ACCESS_DENIED_AMS_SERVICE_ERROR = ACCESS_DENIED
-        | AMS_SERVICE_DEF
+    ACCESS_DENIED_SEC_RESOURCE_OVER_UNSECURE_CHANNEL = ACCESS_DENIED_DEF
+        | SEC_RESOURCE_OVER_UNSECURE_CHANNEL_DEF,
 } SRMAccessResponse_t;
 
 /**
@@ -252,7 +251,8 @@ typedef enum
 
 typedef enum
 {
-    OIC_R_ACL_TYPE = 0,
+    OIC_RESOURCE_TYPE_ERROR = 0,
+    OIC_R_ACL_TYPE,
     OIC_R_AMACL_TYPE,
     OIC_R_CRED_TYPE,
     OIC_R_CRL_TYPE,
diff --git a/resource/csdk/security/src/amsmgr.c b/resource/csdk/security/src/amsmgr.c
deleted file mode 100644 (file)
index 02d9788..0000000
+++ /dev/null
@@ -1,425 +0,0 @@
-//******************************************************************
-//
-// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <string.h>
-#include "oic_malloc.h"
-#include "amsmgr.h"
-#include "resourcemanager.h"
-#include "securevirtualresourcetypes.h"
-#include "srmresourcestrings.h"
-#include "logger.h"
-#include "ocrandom.h"
-#include "aclresource.h"
-#include "amaclresource.h"
-#include "srmutility.h"
-#include "base64.h"
-#include "secureresourcemanager.h"
-#include "doxmresource.h"
-#include "policyengine.h"
-#include "oic_string.h"
-#include "caremotehandler.h"
-
-#define TAG "OIC_SRM_AMSMGR"
-
- //Callback for AMS service multicast discovery request.
-static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
-                         OCClientResponse * clientResponse);
-
-//Callback for unicast secured port discovery request.
-static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandle handle,
-                         OCClientResponse * clientResponse);
-
-//Callback for unicast ACL request
-static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
-    OCClientResponse * clientResponse);
-
-OCStackResult DiscoverAmsService(PEContext_t *context)
-{
-    OIC_LOG(INFO, TAG, "IN DiscoverAmsService");
-
-    OCStackResult ret = OC_STACK_ERROR;
-    const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
-    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
-    OCCallbackData cbData = {.context=NULL};
-
-    VERIFY_NOT_NULL(TAG, context, ERROR);
-    snprintf(uri, sizeof(uri), DOXM_DEVICEID_QUERY_FMT, OIC_RSRC_DOXM_URI,
-                                       OIC_JSON_DEVICE_ID_NAME,
-                                       context->amsMgrContext->amsDeviceId.id);
-
-    cbData.cb = &AmsMgrDiscoveryCallback;
-    cbData.context = (void*)context;
-
-    /* TODO
-     * If no good response was received for this discovery request,
-     * PE would be blocked forever waiting for AMS service to respond with the ACE.
-     * Need logic to reset the PE state and send ACCESS_DENIED response,
-     * when discovery response from AMS service is not received within certain time.
-     */
-    OIC_LOG_V(INFO, TAG,"AMS Manager Sending Multicast Discovery with URI = %s", uri);
-    ret = OCDoResource(NULL, OC_REST_DISCOVER, uri, NULL, NULL,
-                       CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
-
-exit:
-    OIC_LOG(INFO, TAG, "Leaving DiscoverAmsService");
-    return ret;
-}
-
-static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
-                         OCClientResponse * clientResponse)
-{
-    OIC_LOG_V(INFO, TAG, "%s Begin", __func__ );
-
-    if (!ctx ||
-        !clientResponse ||
-        !clientResponse->payload||
-        (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)||
-        (OC_STACK_OK != clientResponse->result))
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
-        return OC_STACK_KEEP_TRANSACTION;
-    }
-
-    (void)handle;
-    PEContext_t *context = (PEContext_t *) ctx;
-    if (context->state != AWAITING_AMS_RESPONSE)
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    OicSecDoxm_t *doxm = NULL;
-
-    OIC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
-          ((OCSecurityPayload*)clientResponse->payload)->securityData);
-    uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
-    size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
-
-    //As doxm is NULL amsmgr can't test if response from trusted AMS service
-    //so keep the transaction.
-    if (OC_STACK_OK == CBORPayloadToDoxm(payload, size, &doxm))
-    {
-        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert CBOR to Binary",__func__);
-        return OC_STACK_KEEP_TRANSACTION;
-    }
-
-    OicUuid_t deviceId = {.id={0}};
-    memcpy(&deviceId, &doxm->deviceID, sizeof(deviceId));
-    DeleteDoxmBinData(doxm);
-
-    /* TODO : By assuming that the first response received is the actual
-     * AMS service, a 'bad device' can cause DoS attack.
-     */
-    if (memcmp(&context->amsMgrContext->amsDeviceId, &deviceId,
-            sizeof(context->amsMgrContext->amsDeviceId)) == 0)
-    {
-        OIC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
-        //Sending Unicast discovery to get secure port information
-        if (OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
-                clientResponse->connType))
-        {
-            context->retVal = ACCESS_WAITING_FOR_AMS;
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-    }
-    context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-    SRMSendResponse(context->retVal);
-    return OC_STACK_DELETE_TRANSACTION;
-}
-
-OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
-                                      OCConnectivityType connType)
-{
-    OIC_LOG(INFO, TAG, "IN SendUnicastSecurePortDiscovery");
-
-    const char RES_DOXM_QUERY_FMT[] = "%s?%s=%s";
-    OCCallbackData cbData = {.context=NULL};
-    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
-    snprintf(uri, sizeof(uri), RES_DOXM_QUERY_FMT, OC_RSRVD_WELL_KNOWN_URI,
-            OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
-
-    cbData.cb = &SecurePortDiscoveryCallback;
-    cbData.context = context;
-
-    OIC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast Discovery with URI = %s", uri);
-
-    return  OCDoResource(NULL, OC_REST_DISCOVER, uri, devAddr, NULL,
-                         connType, OC_LOW_QOS, &cbData, NULL, 0);
-}
-
-static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandle handle,
-                         OCClientResponse * clientResponse)
-{
-    OIC_LOG(INFO, TAG, "In SecurePortDiscoveryCallback");
-
-    if (!ctx ||
-        !clientResponse ||
-        !clientResponse->payload||
-        (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)||
-        (OC_STACK_OK != clientResponse->result))
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
-        SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    PEContext_t *context = (PEContext_t *) ctx;
-
-    (void)handle;
-    if (context->state != AWAITING_AMS_RESPONSE)
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid PE State ", __func__);
-        context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-        SRMSendResponse(context->retVal);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    OCResourcePayload *resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
-
-    //Verifying if the ID of the sender is an AMS service that this device trusts.
-    if(resPayload &&
-       memcmp(context->amsMgrContext->amsDeviceId.id,
-            ((OCDiscoveryPayload*)clientResponse->payload)->sid,
-            // resPayload->sid,
-                    sizeof(context->amsMgrContext->amsDeviceId.id)) != 0)
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid AMS device", __func__);
-        context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-        SRMSendResponse(context->retVal);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    if (resPayload && resPayload->secure)
-    {
-        if(OC_STACK_OK == SendAclReq(context, &clientResponse->devAddr, clientResponse->connType,
-                resPayload->port))
-        {
-            return OC_STACK_DELETE_TRANSACTION;
-        }
-    }
-    OIC_LOG(INFO, TAG, "Can not find secure port information");
-
-    context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-    SRMSendResponse(context->retVal);
-    return OC_STACK_DELETE_TRANSACTION;
-}
-
-OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
-        uint16_t securedPort)
-{
-    OCStackResult ret = OC_STACK_ERROR;
-    const char GET_ACE_QUERY_FMT[] = "%s?%s=%s;%s=%s";
-    char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
-    OCCallbackData cbData = {.context=NULL};
-    OCDevAddr destAddr = {.adapter = OC_ADAPTER_IP};
-    char *subID = NULL;
-
-    VERIFY_NOT_NULL(TAG, context, ERROR);
-    VERIFY_NOT_NULL(TAG, devAddr, ERROR);
-
-    ret = ConvertUuidToStr(&context->subject, &subID);
-    if(OC_STACK_OK != ret)
-    {
-        OIC_LOG(ERROR, TAG, "SendAclReq : Failed to canonical UUID encoding");
-        return OC_STACK_ERROR;
-    }
-
-    snprintf(uri, sizeof(uri), GET_ACE_QUERY_FMT, OIC_RSRC_ACL_URI,
-                                    OIC_JSON_SUBJECTID_NAME, subID,
-                                    OIC_JSON_RESOURCES_NAME, context->resource);
-    OICFree(subID);
-
-    cbData.cb = &AmsMgrAclReqCallback;
-    cbData.context = context;
-
-    destAddr = *devAddr;
-    //update port info
-    destAddr.flags = (OCTransportFlags)(destAddr.flags | OC_FLAG_SECURE);
-    destAddr.port = securedPort;
-
-    OIC_LOG_V(INFO, TAG, "AMS Manager Sending Unicast ACL request with URI = %s", uri);
-    ret = OCDoResource(NULL, OC_REST_GET, uri, &destAddr, NULL,
-            connType, OC_LOW_QOS, &cbData, NULL, 0);
-
-exit:
-    OIC_LOG_V(INFO, TAG, "%s returns %d ", __func__, ret);
-    return ret;
-}
-
-static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
-    OCClientResponse * clientResponse)
-{
-    OIC_LOG_V(INFO, TAG, "%s Begin", __func__ );
-
-    (void)handle;
-    PEContext_t *context = (PEContext_t *) ctx;
-    SRMAccessResponse_t rsps;
-
-    if (!ctx ||
-        !clientResponse ||
-        !clientResponse->payload||
-        (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type) ||
-        (clientResponse->result != OC_STACK_OK))
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid Response ", __func__);
-        SRMSendResponse(ACCESS_DENIED_AMS_SERVICE_ERROR);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    if (context->state != AWAITING_AMS_RESPONSE)
-    {
-        OIC_LOG_V(ERROR, TAG, "%s Invalid State ", __func__);
-        context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-        SRMSendResponse(context->retVal);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-    // Verify before installing ACL if the ID of the sender of this ACL is an AMS
-    //service that this device trusts.
-    rsps = ACCESS_DENIED;
-    if((UUID_LENGTH == clientResponse->identity.id_length) &&
-        memcmp(context->amsMgrContext->amsDeviceId.id, clientResponse->identity.id,
-                       sizeof(context->amsMgrContext->amsDeviceId.id)) == 0)
-    {
-        size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
-        OCStackResult ret =
-                AppendACL(((OCSecurityPayload*)clientResponse->payload)->securityData, size);
-        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
-
-        OIC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
-        rsps = CheckPermission(context, &context->subject, context->resource, context->permission);
-        VERIFY_SUCCESS(TAG, (true == IsAccessGranted(rsps)), ERROR);
-
-        OIC_LOG_V(INFO, TAG, "%sAccess granted, Calling SRMCallCARequestHandler", __func__);
-        context->retVal = ACCESS_GRANTED;
-        SRMSendResponse(context->retVal);
-        return OC_STACK_DELETE_TRANSACTION;
-    }
-
-exit:
-    context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-    SRMSendResponse(context->retVal);
-    return OC_STACK_DELETE_TRANSACTION;
-}
-
-OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
-                        const CARequestInfo_t *requestInfo)
-{
-    OCStackResult ret = OC_STACK_INVALID_PARAM;
-    VERIFY_NOT_NULL(TAG, context->amsMgrContext, ERROR);
-    ret = OC_STACK_ERROR;
-
-    //The AmsMgr context endpoint and requestInfo will be free from ,
-    //AmsMgrAclReqCallback function
-    if (context->amsMgrContext->endpoint)
-    {
-        OICFree(context->amsMgrContext->endpoint);
-        context->amsMgrContext->endpoint = NULL;
-    }
-    context->amsMgrContext->endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof(CAEndpoint_t ));
-    VERIFY_NOT_NULL(TAG, context->amsMgrContext->endpoint, ERROR);
-    *context->amsMgrContext->endpoint = *endpoint;
-
-    if (context->amsMgrContext->requestInfo)
-    {
-        FreeCARequestInfo(context->amsMgrContext->requestInfo);
-        context->amsMgrContext->requestInfo = NULL;
-    }
-    context->amsMgrContext->requestInfo = CACloneRequestInfo(requestInfo);
-    VERIFY_NOT_NULL(TAG, context->amsMgrContext->requestInfo, ERROR);
-    ret = OC_STACK_OK;
-exit:
-    return ret;
-}
-
-void FreeCARequestInfo(CARequestInfo_t *requestInfo)
-{
-    if (NULL == requestInfo)
-    {
-        OIC_LOG_V(DEBUG, TAG, "%s: Can't free memory. Received NULL requestInfo", __func__);
-        return;
-    }
-    OICFree(requestInfo->info.token);
-    OICFree(requestInfo->info.options);
-    OICFree(requestInfo->info.payload);
-    OICFree(requestInfo->info.resourceUri);
-    OICFree(requestInfo);
-}
-
-
-//This method checks for Amacl resource. If Amacl is found then it fills up
-//context->amsMgrContext->amsDeviceId with amsID of the Amacl else leaves it empty.
-bool FoundAmaclForRequest(PEContext_t *context)
-{
-    OIC_LOG_V(INFO, TAG, "%s:no ACL found. Searching for AMACL",__func__);
-
-    bool ret = false;
-    VERIFY_NOT_NULL(TAG, context, ERROR);
-    memset(&context->amsMgrContext->amsDeviceId, 0, sizeof(context->amsMgrContext->amsDeviceId));
-
-    //Call amacl resource function to get the AMS service deviceID for the resource
-    if (OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
-    {
-        OIC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
-                __func__, context->resource);
-        ret = true;
-    }
-    else
-    {
-        OIC_LOG_V(INFO, TAG, "%s:AMACL not found for the requested resource %s",
-                __func__, context->resource);
-        ret = false;
-    }
-
- exit:
-     return ret;
-}
-
-void ProcessAMSRequest(PEContext_t *context)
-{
-    OicUuid_t  emptyUuid = {.id={0}};
-    OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
-    if (NULL != context)
-    {
-        if((ACCESS_GRANTED != context->retVal) && (false == context->amsProcessing))
-        {
-            context->amsProcessing = true;
-
-            //Checking if context AMS deviceId is empty
-            if(memcmp(&context->amsMgrContext->amsDeviceId, &emptyUuid, sizeof(OicUuid_t)) != 0 )
-            {
-                if(OC_STACK_OK == DiscoverAmsService(context))
-                {
-                    context->retVal = ACCESS_WAITING_FOR_AMS;
-                    OIC_LOG_V(INFO, TAG, "Leaving %s(WAITING_FOR_AMS)", __func__);
-                    context->state = AWAITING_AMS_RESPONSE;
-                }
-                else
-                {
-                    context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
-                }
-            }
-        }
-    }
-    else
-    {
-        OIC_LOG_V(INFO, TAG, "Leaving %s(context is NULL)", __func__);
-    }
-}
index 534faf3..8376fdf 100644 (file)
@@ -22,7 +22,6 @@
 #include "utlist.h"
 #include "oic_malloc.h"
 #include "policyengine.h"
-#include "amsmgr.h"
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
@@ -93,40 +92,12 @@ static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
     return true;
 }
 
-void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
-{
-    if (NULL == context)
-    {
-        return;
-    }
-
-    // Clear stateful context variables.
-    memset(&context->subject, 0, sizeof(context->subject));
-    memset(&context->resource, 0, sizeof(context->resource));
-    context->permission = 0x0;
-    context->amsProcessing = false;
-    context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
-
-    if (context->amsMgrContext)
-    {
-        if (context->amsMgrContext->requestInfo)
-        {
-            FreeCARequestInfo(context->amsMgrContext->requestInfo);
-        }
-        OICFree(context->amsMgrContext->endpoint);
-        memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
-    }
-
-    // Set state.
-    context->state = state;
-}
-
 /**
  * Compare the request's subject to DevOwner.
  *
  * @return true if context->subjectId == GetDoxmDevOwner(), else false.
  */
-static bool IsRequestFromDevOwner(PEContext_t *context)
+static bool IsRequestFromDevOwner(SRMRequestContext_t *context)
 {
     bool retVal = false;
 
@@ -146,7 +117,7 @@ static bool IsRequestFromDevOwner(PEContext_t *context)
     OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
     if (doxm)
     {
-        retVal = UuidCmp(&doxm->owner, &context->subject);
+        retVal = UuidCmp(&doxm->owner, &context->subjectUuid);
     }
     return retVal;
 }
@@ -158,7 +129,7 @@ static bool IsRequestFromDevOwner(PEContext_t *context)
  *
  * @return true if context->subjectId exist subowner list, else false.
  */
-static bool IsRequestFromSubOwner(PEContext_t *context)
+static bool IsRequestFromSubOwner(SRMRequestContext_t *context)
 {
     bool retVal = false;
 
@@ -167,7 +138,7 @@ static bool IsRequestFromSubOwner(PEContext_t *context)
         return retVal;
     }
 
-    if(IsSubOwner(&context->subject))
+    if(IsSubOwner(&context->subjectUuid))
     {
         retVal = true;
     }
@@ -190,7 +161,7 @@ static bool IsRequestFromSubOwner(PEContext_t *context)
  *
  * @return true if request is valid, else false.
  */
-static bool IsValidRequestFromSubOwner(PEContext_t *context)
+static bool IsValidRequestFromSubOwner(SRMRequestContext_t *context)
 {
     bool isValidRequest = false;
 
@@ -203,7 +174,7 @@ static bool IsValidRequestFromSubOwner(PEContext_t *context)
     {
         case OIC_R_DOXM_TYPE:
             //SubOwner has READ permission only for DOXM
-            if(PERMISSION_READ == context->permission)
+            if(PERMISSION_READ == context->requestedPermission)
             {
                 isValidRequest = true;
             }
@@ -214,11 +185,13 @@ static bool IsValidRequestFromSubOwner(PEContext_t *context)
             break;
         case OIC_R_CRED_TYPE:
             //SubOwner can only access the credential which is registered as the eowner.
-            isValidRequest = IsValidCredentialAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
+            isValidRequest = IsValidCredentialAccessForSubOwner(&context->subjectUuid,
+             context->payload, context->payloadSize);
             break;
         case OIC_R_ACL_TYPE:
             //SubOwner can only access the ACL which is registered as the eowner.
-            isValidRequest = IsValidAclAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
+            isValidRequest = IsValidAclAccessForSubOwner(&context->subjectUuid,
+                context->payload, context->payloadSize);
             break;
         default:
             //SubOwner has full permission for all resource except the security resource
@@ -287,7 +260,7 @@ static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
  *
  * @return true if context->subjectId equals SVR rowner id, else return false
  */
-bool IsRequestFromResourceOwner(PEContext_t *context)
+bool IsRequestFromResourceOwner(SRMRequestContext_t *context)
 {
     bool retVal = false;
     OicUuid_t resourceOwner;
@@ -302,7 +275,7 @@ bool IsRequestFromResourceOwner(PEContext_t *context)
     {
         if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
         {
-            retVal = UuidCmp(&context->subject, &resourceOwner);
+            retVal = UuidCmp(&context->subjectUuid, &resourceOwner);
         }
     }
 
@@ -318,19 +291,6 @@ bool IsRequestFromResourceOwner(PEContext_t *context)
     return retVal;
 }
 
-INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
-{
-    OicUuid_t emptySubject = {.id={0}};
-
-    if(NULL == context)
-    {
-        return false;
-    }
-
-    return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
-            true : false;
-}
-
 /**
  * Bitwise check to see if 'permission' contains 'request'.
  *
@@ -376,33 +336,6 @@ INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
 }
 
 /**
- * Copy the subject, resource and permission into the context fields.
- */
-static void CopyParamsToContext(PEContext_t     *context,
-                                const OicUuid_t *subjectId,
-                                const char      *resource,
-                                const uint16_t  requestedPermission)
-{
-    size_t length = 0;
-
-    if (NULL == context || NULL == subjectId || NULL == resource)
-    {
-        return;
-    }
-
-    memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
-
-    // Copy the resource string into context.
-    length = sizeof(context->resource) - 1;
-    strncpy(context->resource, resource, length);
-    context->resource[length] = '\0';
-
-
-    // Assign the permission field.
-    context->permission = requestedPermission;
-}
-
-/**
  * Check whether 'resource' is getting accessed within the valid time period.
  *
  * @param acl is the ACL to check.
@@ -430,7 +363,7 @@ static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
     {
         for(size_t i = 0; i < validity->recurrenceLen; i++)
         {
-            if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(validity->period,
+            if (IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(validity->period,
                 validity->recurrences[i]))
             {
                 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
@@ -454,7 +387,7 @@ static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
  *
  * @return true if 'resource' found, otherwise false.
  */
- static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
+static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
 {
     if (NULL== ace || NULL == resource)
     {
@@ -483,24 +416,27 @@ static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
  * Set context->retVal to result from first ACL found which contains
  * correct subject AND resource.
  */
-static void ProcessAccessRequest(PEContext_t *context)
+static void ProcessAccessRequest(SRMRequestContext_t *context)
 {
+    OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest().");
+
     if (NULL != context)
     {
         const OicSecAce_t *currentAce = NULL;
-        OicSecAce_t *savePtr = NULL;
+        OicSecAce_t *aceSavePtr = NULL;
 
-        OIC_LOG_V(DEBUG, TAG, "Entering ProcessAccessRequest(%s)", context->resource);
+        OIC_LOG_V(DEBUG, TAG, "Entering ProcessAccessRequest(%s)",
+            context->resourceUri);
 
         // Start out assuming subject not found.
-        context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
+        context->responseVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
 
         // Loop through all ACLs with a matching Subject searching for the right
         // ACL for this request.
         do
         {
             OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
-            currentAce = GetACLResourceData(&context->subject, &savePtr);
+            currentAce = GetACLResourceData(&context->subjectUuid, &aceSavePtr);
 
             if (NULL != currentAce)
             {
@@ -508,31 +444,34 @@ static void ProcessAccessRequest(PEContext_t *context)
                 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
 
                 // Subject was found, so err changes to Rsrc not found for now.
-                context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
+                context->responseVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
-                if (IsResourceInAce(context->resource, currentAce))
+                if (IsResourceInAce(context->resourceUri, currentAce))
                 {
                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
 
                     // Found the resource, so it's down to valid period & permission.
-                    context->retVal = ACCESS_DENIED_INVALID_PERIOD;
+                    context->responseVal = ACCESS_DENIED_INVALID_PERIOD;
                     if (IsAccessWithinValidTime(currentAce))
                     {
-                        context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
-                        if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
+                        context->responseVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
+                        if (IsPermissionAllowingRequest(currentAce->permission,
+                            context->requestedPermission))
                         {
-                            context->retVal = ACCESS_GRANTED;
+                            context->responseVal = ACCESS_GRANTED;
                         }
                     }
                 }
             }
             else
             {
-                OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
+                OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",
+                    __func__, context->resourceUri);
             }
-        } while ((NULL != currentAce) && (ACCESS_GRANTED != context->retVal));
+        } while ((NULL != currentAce)
+            && (false == IsAccessGranted(context->responseVal)));
 
-        if (IsAccessGranted(context->retVal))
+        if (IsAccessGranted(context->responseVal))
         {
             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
         }
@@ -545,152 +484,89 @@ static void ProcessAccessRequest(PEContext_t *context)
     {
         OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
     }
+
+    return;
 }
 
-SRMAccessResponse_t CheckPermission(PEContext_t     *context,
-                                    const OicUuid_t *subjectId,
-                                    const char      *resource,
-                                    const uint16_t  requestedPermission)
+void CheckPermission(SRMRequestContext_t *context)
 {
-    SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
-
-    VERIFY_NOT_NULL(TAG, context, ERROR);
-    VERIFY_NOT_NULL(TAG, subjectId, ERROR);
-    VERIFY_NOT_NULL(TAG, resource, ERROR);
+    bool isDeviceOwned = false;
 
-    // Each state machine context can only be processing one request at a time.
-    // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
-    // state, return error. Otherwise, change to BUSY state and begin processing request.
-    if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
+    if(NULL == context)
     {
-        if (AWAITING_REQUEST == context->state)
-        {
-            SetPolicyEngineState(context, BUSY);
-            CopyParamsToContext(context, subjectId, resource, requestedPermission);
-        }
-
-        // Before doing any ACL processing, check if request a) coming
-        // from DevOwner AND b) the device is in Ready for OTM or Reset state
-        // (which in IoTivity is equivalent to isOp == false && owned == false)
-        // AND c) the request is for a SVR resource.
-        // If all 3 conditions are met, grant request.
-        bool isDeviceOwned = true; // default to value that will not grant access
-        if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
-        {
-            context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
-        }
-        // If we were able to get the value of doxm->isOwned, proceed with
-        // test for implicit access...
-        else if (IsRequestFromDevOwner(context) // if from DevOwner
-        && (GetPstatIsop() == false) // AND if pstat->isOp == false
-        && (isDeviceOwned == false) // AND if doxm->isOwned == false
-        && (context->resourceType != NOT_A_SVR_RESOURCE)) // AND if SVR type
-        {
-            context->retVal = ACCESS_GRANTED;
-        }
-        // If not granted via DevOwner status and not a subowner,
-        // then check if request is for a SVR and coming from rowner
-        else if (IsRequestFromResourceOwner(context))
-        {
-            context->retVal = ACCESS_GRANTED;
-        }
-#ifdef MULTIPLE_OWNER
-        //Then check if request from SubOwner
-        else if(IsRequestFromSubOwner(context))
-        {
-            if(IsValidRequestFromSubOwner(context))
-            {
-                context->retVal = ACCESS_GRANTED;
-            }
-        }
-#endif //MULTIPLE_OWNER
-        // Else request is a "normal" request that must be tested against ACL
-        else
-        {
-            OicUuid_t saveSubject = {.id={0}};
-            bool isSubEmpty = IsRequestSubjectEmpty(context);
-
-            ProcessAccessRequest(context);
-
-            // If access not already granted, and requested subject != wildcard,
-            // try looking for a wildcard ACE that grants access.
-            if ((ACCESS_GRANTED != context->retVal) && \
-              (false == IsWildCardSubject(&context->subject)))
-            {
-                //Saving subject for Amacl check
-                memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
-
-                //Setting context subject to WILDCARD_SUBJECT_ID
-                //TODO: change ProcessAccessRequest method signature to
-                //ProcessAccessRequest(context, subject) so that context
-                //subject is not tempered.
-                memset(&context->subject, 0, sizeof(context->subject));
-                memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
-                ProcessAccessRequest(context); // TODO anonymous subj can result
-                                               // in confusing err code return.
-            }
-
-            //No local ACE found for the request so checking Amacl resource
-            if (ACCESS_GRANTED != context->retVal)
-            {
-                //If subject is not empty then restore the original subject
-                //else keep the subject to WILDCARD_SUBJECT_ID
-                if(!isSubEmpty)
-                {
-                    memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
-                }
-
-                //FoundAmaclForRequest method checks for Amacl and fills up
-                //context->amsMgrContext->amsDeviceId with the AMS deviceId
-                //if Amacl was found for the requested resource.
-                if(FoundAmaclForRequest(context))
-                {
-                    ProcessAMSRequest(context);
-                }
-            }
-        }
+        OIC_LOG_V(ERROR, TAG, "NULL context; access denied.");
+        context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
+        return;
     }
-    else
+
+    // Before doing any ACL processing, check if request is a) coming
+    // from DevOwner AND b) the device is in Ready for OTM or Reset state
+    // (which in IoTivity is equivalent to isOp == false && owned == false)
+    // AND c) the request is for a SVR resource.
+    // If all 3 conditions are met, grant request.
+    // TODO_IoTivity_1.3: use pstat.dos instead of these two checks.
+    isDeviceOwned = true; // default to value that will NOT grant access
+    if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
     {
-        context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
+        OIC_LOG_V(ERROR, TAG, "GetDoxmIsOwned() call failed.");
+        context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
     }
-
-    // Capture retVal before resetting state for next request.
-    retVal = context->retVal;
-
-   if (!context->amsProcessing)
+    // If we were able to get the value of doxm->isOwned, proceed with
+    // test for implicit access.
+    else if (IsRequestFromDevOwner(context) &&  // if from DevOwner
+            !GetPstatIsop() &&                  // AND if pstat->isOp == false
+            !isDeviceOwned &&                   // AND if doxm->isOwned == false
+            (NOT_A_SVR_RESOURCE != context->resourceType)) // AND if is SVR type
     {
-        OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
-        SetPolicyEngineState(context, AWAITING_REQUEST);
+        context->responseVal = ACCESS_GRANTED;
     }
-
-exit:
-    return retVal;
-}
-
-OCStackResult InitPolicyEngine(PEContext_t *context)
-{
-    if(NULL == context)
+    // If not granted via DevOwner status and not a subowner,
+    // then check if request is for a SVR and coming from rowner
+    else if (IsRequestFromResourceOwner(context))
     {
-        return OC_STACK_ERROR;
+        context->responseVal = ACCESS_GRANTED;
     }
-
-    context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
-    if(NULL == context->amsMgrContext)
+#ifdef MULTIPLE_OWNER // TODO Samsung reviewer: per above comment, should this
+                      // go above IsRequestFromResourceOwner() call, or here?
+    // Then check if request from SubOwner.
+    else if(IsRequestFromSubOwner(context))
     {
-        return OC_STACK_ERROR;
+        if(IsValidRequestFromSubOwner(context))
+        {
+            context->responseVal = ACCESS_GRANTED;
+        }
     }
+#endif //MULTIPLE_OWNER
+    // Else request is a "normal" request that must be tested against ACL.
+    else
+    {
+        OicUuid_t saveSubjectUuid = {.id={0}};
+        // bool isSubEmpty = IsRequestSubjectEmpty(context);
 
-    SetPolicyEngineState(context, AWAITING_REQUEST);
-    return OC_STACK_OK;
-}
+        ProcessAccessRequest(context);
 
-void DeInitPolicyEngine(PEContext_t *context)
-{
-    if(NULL != context)
-    {
-        SetPolicyEngineState(context, STOPPED);
-        OICFree(context->amsMgrContext);
+        // TODO_IoTivity_1.3: ensure check order results in Union permissions
+        // If access not already granted, and requested subject != wildcard,
+        // try looking for a wildcard ACE that grants access.
+        // See JIRA ticket 1795 (https://jira.iotivity.org/browse/IOT-1795)
+        if (ACCESS_GRANTED != context->responseVal &&
+            !IsWildCardSubject(&context->subjectUuid))
+        {
+            // Save subject to restore context after wildcard subject check.
+            memcpy(&saveSubjectUuid, &context->subjectUuid,
+                sizeof(context->subjectUuid));
+
+            // Set context->subjectUuid to WILDCARD_SUBJECT_ID.
+            memset(&context->subjectUuid, 0, sizeof(context->subjectUuid));
+            memcpy(&context->subjectUuid,
+                &WILDCARD_SUBJECT_ID, sizeof(context->subjectUuid));
+            ProcessAccessRequest(context);
+
+            // Restore subjectUuid.
+            memcpy(&context->subjectUuid,
+                &saveSubjectUuid, sizeof(context->subjectUuid));
+        }
     }
+
     return;
-}
+}
\ No newline at end of file
index 9dbcdc1..27dd0c7 100644 (file)
@@ -26,7 +26,6 @@
 #include "credresource.h"
 #include "policyengine.h"
 #include "srmutility.h"
-#include "amsmgr.h"
 #include "oic_string.h"
 #include "oic_malloc.h"
 #include "securevirtualresourcetypes.h"
@@ -49,39 +48,10 @@ static CAErrorCallback gErrorHandler = NULL;
 static SPResponseCallback gSPResponseHandler = NULL;
 
 /**
- * A single global Policy Engine context will suffice as long
+ * A single global Request context will suffice as long
  * as SRM is single-threaded.
  */
-PEContext_t g_policyEngineContext;
-
-
-/**
- * Function to retrieve the length of the resource URI address part.
- *
- * @param resourceUri   A null-terminated string representing the resource URI.
- *
- * @return  Length of the resource URI address or -1, if failed.
- */
-static int GetResourceUriAddressLength(CAURI_t resourceUri)
-{
-    if (!resourceUri)
-    {
-        OIC_LOG(ERROR, TAG, "Missing resource URI");
-        return -1;
-    }
-
-    size_t resourceUriLength = strlen(resourceUri);
-    if (resourceUriLength > MAX_URI_LENGTH)
-    {
-        OIC_LOG(ERROR, TAG, "Invalid resource URI length");
-        return -1;
-    }
-
-    //Check the URI has the query and skip it before checking the permission
-    char *uri = strstr(resourceUri, "?");
-
-    return uri ? (int)(uri - resourceUri) : (int)resourceUriLength;
-}
+SRMRequestContext_t g_requestContext;
 
 /**
  * Function to register provisoning API's response callback.
@@ -92,201 +62,264 @@ void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
     gSPResponseHandler = respHandler;
 }
 
-void SetResourceRequestType(PEContext_t *context, const char *resourceUri)
+void SetRequestedResourceType(SRMRequestContext_t *context)
 {
-    context->resourceType = GetSvrTypeFromUri(resourceUri);
+    context->resourceType = GetSvrTypeFromUri(context->resourceUri);
 }
 
-static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
+// Send the response (context->responseInfo) to the requester
+// (context->endPoint).
+static void SRMSendResponse(SRMRequestContext_t *context)
 {
-    CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
-
-    if (NULL == context ||
-       NULL == context->amsMgrContext->requestInfo)
+    if (NULL != context
+        && NULL != context->requestInfo
+        && NULL != context->endPoint)
     {
-        OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
-        return;
-    }
-
-    memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
-            sizeof(responseInfo.info));
-    responseInfo.info.payload = NULL;
-    responseInfo.result = CA_UNAUTHORIZED_REQ;
-    responseInfo.info.dataType = CA_RESPONSE_DATA;
 
-    if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
-    {
-        OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
+        if (CA_STATUS_OK == CASendResponse(context->endPoint,
+            &(context->responseInfo)))
+        {
+            OIC_LOG_V(DEBUG, TAG, "SRM response sent.");
+            context->responseSent = true;
+        }
+        else
+        {
+            OIC_LOG_V(ERROR, TAG, "SRM response failed.");
+        }
     }
     else
     {
-        OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
+        OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
     }
+
+    return;
 }
 
-void SRMSendResponse(SRMAccessResponse_t responseVal)
+// Based on the context->responseVal, either call the entity handler for the
+// request (which must send the response), or send an ACCESS_DENIED response.
+void SRMGenerateResponse(SRMRequestContext_t *context)
 {
-    OIC_LOG(DEBUG, TAG, "Sending response to remote device");
+    OIC_LOG_V(INFO, TAG, "%s : entering function.", __func__);
 
-    if (IsAccessGranted(responseVal) && gRequestHandler)
+    // If Access Granted, validate parameters and then pass request
+    // on to resource endpoint.
+    if (IsAccessGranted(context->responseVal))
     {
-        OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
-        if (!g_policyEngineContext.amsMgrContext->endpoint ||
-            !g_policyEngineContext.amsMgrContext->requestInfo)
+        if(NULL != gRequestHandler
+            && NULL != context->endPoint
+            && NULL != context->requestInfo)
+        {
+            OIC_LOG_V(INFO, TAG, "%s : Access granted, passing req to endpoint.",
+             __func__);
+            gRequestHandler(context->endPoint, context->requestInfo);
+            context->responseSent = true; // SRM counts on the endpoint to send
+                                          // a response.
+        }
+        else // error condition; log relevant msg then send DENIED response
         {
-            OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
-            SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
-            goto exit;
+            OIC_LOG_V(ERROR, TAG, "%s : Null values in context.", __func__);
+            context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
+            context->responseInfo.result = CA_INTERNAL_SERVER_ERROR;
+            SRMSendResponse(context);
         }
-        gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
-                g_policyEngineContext.amsMgrContext->requestInfo);
     }
-    else
+    else // Access Denied
     {
-        OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
-        SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
+        OIC_LOG_V(INFO, TAG, "%s : Access Denied; sending CA_UNAUTHORIZED_REQ.",
+         __func__);
+        // TODO: in future version, differentiate between types of DENIED.
+        // See JIRA issue 1796 (https://jira.iotivity.org/browse/IOT-1796)
+        context->responseInfo.result = CA_UNAUTHORIZED_REQ;
+        SRMSendResponse(context);
     }
-
-exit:
-    //Resetting PE state to AWAITING_REQUEST
-    SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
+    return;
 }
 
-/**
- * Handle the request from the SRM.
- *
- * @param endPoint object from which the response is received.
- * @param requestInfo contains information for the request.
- */
-void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
+// Set the value of context->resourceUri, based on the context->requestInfo.
+void SetResourceUriAndType(SRMRequestContext_t *context)
 {
-    OIC_LOG(DEBUG, TAG, "Received request from remote device");
+    char *uri = strstr(context->requestInfo->info.resourceUri, "?");
+    size_t position = 0;
 
-    bool isRequestOverSecureChannel = false;
-    if (!endPoint || !requestInfo)
+    if (uri)
     {
-        OIC_LOG(ERROR, TAG, "Invalid arguments");
-        return;
+        //Skip query and pass the resource uri
+        position = uri - context->requestInfo->info.resourceUri;
     }
-
-    // Copy the subjectID
-    OicUuid_t subjectId = {.id = {0}};
-    OicUuid_t nullSubjectId = {.id = {0}};
-    memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
-
-    //If subject id is null that means request is sent thru coap.
-    if ( (endPoint->flags & CA_SECURE)
-         || (memcmp(subjectId.id, nullSubjectId.id, sizeof(subjectId.id)) != 0))
+    else
     {
-        OIC_LOG(INFO, TAG, "request over secure channel");
-        isRequestOverSecureChannel = true;
+        position = strlen(context->requestInfo->info.resourceUri);
     }
-
-    CAURI_t resourceUri = requestInfo->info.resourceUri;
-    int resourceUriAddressLength = GetResourceUriAddressLength(resourceUri);
-
-    if (resourceUriAddressLength < 0)
+    if (MAX_URI_LENGTH < position  || 0 > position)
     {
+        OIC_LOG_V(ERROR, TAG, "Incorrect URI length.");
         return;
     }
+    OICStrcpyPartial(context->resourceUri, MAX_URI_LENGTH + 1,
+        context->requestInfo->info.resourceUri, position);
 
-    SRMAccessResponse_t response = ACCESS_DENIED;
-    char newUri[MAX_URI_LENGTH + 1];
-    OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, resourceUri, resourceUriAddressLength);
-
-    SetResourceRequestType(&g_policyEngineContext, newUri);
+    // Set the resource type.
+    context->resourceType = GetSvrTypeFromUri(context->resourceUri);
 
-     // Form a 'Error', 'slow response' or 'access deny' response and send to peer
-    CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
-    memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
-    responseInfo.info.payload = NULL;
-    responseInfo.info.dataType = CA_RESPONSE_DATA;
+    return;
+}
 
-    OCResource *resPtr = FindResourceByUri(newUri);
-    if (NULL != resPtr)
+// Check if this request is asking to access a "sec" = true resource
+// over an unsecure channel.  This type of request is forbidden with
+// the exception of a few SVRs (see Security Specification).
+void CheckRequestForSecResourceOverUnsecureChannel(SRMRequestContext_t *context)
+{
+    // if request is over unsecure channel, check resource type
+    if(false == context->secureChannel)
     {
-        // All vertical secure resources and SVR resources other than DOXM & PSTAT should reject request
-        // over coap.
-        if ((((resPtr->resourceProperties) & OC_SECURE)
-                            && (g_policyEngineContext.resourceType == NOT_A_SVR_RESOURCE))
-                            || ((g_policyEngineContext.resourceType < OIC_SEC_SVR_TYPE_COUNT)
-                            &&  (g_policyEngineContext.resourceType != OIC_R_DOXM_TYPE)
-                            &&  (g_policyEngineContext.resourceType != OIC_R_PSTAT_TYPE)))
+        OCResource *resPtr = FindResourceByUri(context->resourceUri);
+        if (NULL != resPtr)
         {
-           // if resource is secure and request is over insecure channel
-            if (!isRequestOverSecureChannel)
+            // All vertical secure resources and SVR resources other than
+            // DOXM & PSTAT should reject requests over unsecure channel.
+            if ((((resPtr->resourceProperties) & OC_SECURE)
+                && (context->resourceType == NOT_A_SVR_RESOURCE))
+                || ((context->resourceType < OIC_SEC_SVR_TYPE_COUNT)
+                    && (context->resourceType != OIC_R_DOXM_TYPE)
+                    && (context->resourceType != OIC_R_PSTAT_TYPE)))
             {
                 // Reject all the requests over coap for secure resource.
-                responseInfo.result = CA_FORBIDDEN_REQ;
-                if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
-                {
-                    OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
-                }
-                return;
+                context->responseVal = ACCESS_DENIED_SEC_RESOURCE_OVER_UNSECURE_CHANNEL;
+                context->responseInfo.result = CA_FORBIDDEN_REQ;
+                SRMSendResponse(context);
             }
         }
     }
-#ifdef MULTIPLE_OWNER
-    /*
-     * In case of ACL and CRED, The payload required to verify the payload.
-     * Payload information will be used for subowner's permission verification.
-     */
-    g_policyEngineContext.payload = (uint8_t*)requestInfo->info.payload;
-    g_policyEngineContext.payloadSize = requestInfo->info.payloadSize;
-#endif //MULTIPLE_OWNER
 
-    //New request are only processed if the policy engine state is AWAITING_REQUEST.
-    if (AWAITING_REQUEST == g_policyEngineContext.state)
+    return;
+}
+
+void ClearRequestContext(SRMRequestContext_t *context)
+{
+    if (NULL == context)
     {
-        OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
-                resourceUri, requestInfo->method);
-        response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
-                GetPermissionFromCAMethod_t(requestInfo->method));
+
+        OIC_LOG(ERROR, TAG, "Null context.");
     }
     else
     {
-        OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
-                g_policyEngineContext.state, resourceUri, requestInfo->method);
+        // Clear context variables.
+        context->endPoint = NULL;
+        context->resourceType = OIC_RESOURCE_TYPE_ERROR;
+        memset(&context->resourceUri, 0, sizeof(context->resourceUri));
+        context->requestedPermission = PERMISSION_ERROR;
+        memset(&context->responseInfo, 0, sizeof(context->responseInfo));
+        context->responseSent = false;
+        context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
+        context->requestInfo = NULL;
+        context->secureChannel = false;
+        context->slowResponseSent = false;
+        context->subjectIdType = SUBJECT_ID_TYPE_ERROR;
+        memset(&context->subjectUuid, 0, sizeof(context->subjectUuid));
+#ifdef MULTIPLE_OWNER
+        memset(&context->payload, 0, context->payloadSize); // TODO Samsung reviewer: please confirm
+        context->payloadSize = 0; // TODO Samsung reviewer: please confirm
+#endif //MULTIPLE_OWNER
     }
 
-    if (IsAccessGranted(response) && gRequestHandler)
+    return;
+}
+
+// Returns true iff Request arrived over secure channel
+bool isRequestOverSecureChannel(SRMRequestContext_t *context)
+{
+    OicUuid_t nullSubjectId = {.id = {0}};
+
+    // if flag set, return true
+    if(context->endPoint->flags & CA_SECURE)
     {
-        gRequestHandler(endPoint, requestInfo);
-        return;
+        return true;
+    }
+    // a null subject ID indicates CoAP, so if non-null, also return true
+    else if(memcmp(context->requestInfo->info.identity.id,
+        nullSubjectId.id, sizeof(context->requestInfo->info.identity.id)) != 0)
+    {
+        return true;
     }
 
-    VERIFY_NOT_NULL(TAG, gRequestHandler, ERROR);
+    return false;
+}
 
-    if (ACCESS_WAITING_FOR_AMS == response)
-    {
-        OIC_LOG(INFO, TAG, "Sending slow response");
+/**
+ * Entry point into SRM, called by lower layer to determine whether an incoming
+ * request should be GRANTED or DENIED.
+ *
+ * @param endPoint object from which the response is received.
+ * @param requestInfo contains information for the request.
+ */
+void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
+{
+    OIC_LOG(DEBUG, TAG, "Received request from remote device");
+
+    SRMRequestContext_t *ctx = &g_requestContext; // Always use our single ctx for now.
+
+    ClearRequestContext(ctx);
 
-        UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
-        responseInfo.result = CA_EMPTY;
-        responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
+    if (!endPoint || !requestInfo)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid endPoint or requestInfo; can't process.");
     }
     else
     {
-        /*
-         * TODO Enhance this logic more to decide between
-         * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
-         * upon SRMAccessResponseReasonCode_t
-         */
-        OIC_LOG(INFO, TAG, "Sending for regular response");
-        responseInfo.result = CA_UNAUTHORIZED_REQ;
+        // Store the endpoint and requestinfo params.
+        ctx->endPoint = endPoint;
+        ctx->requestInfo = requestInfo;
+
+        // Copy the subjectID.
+        memcpy(ctx->subjectUuid.id,
+            requestInfo->info.identity.id, sizeof(ctx->subjectUuid.id));
+        ctx->subjectIdType = SUBJECT_ID_TYPE_UUID; // only supported type for now
+
+        // Set secure channel boolean.
+        ctx->secureChannel = isRequestOverSecureChannel(ctx);
+
+        // Set resource URI and type.
+        SetResourceUriAndType(ctx);
+
+        // Initialize responseInfo.
+        memcpy(&(ctx->responseInfo.info), &(requestInfo->info),
+            sizeof(ctx->responseInfo.info));
+        ctx->responseInfo.info.payload = NULL;
+        ctx->responseInfo.result = CA_INTERNAL_SERVER_ERROR;
+        ctx->responseInfo.info.dataType = CA_RESPONSE_DATA;
+
+        // Before consulting ACL, check if this is a forbidden request type.
+        CheckRequestForSecResourceOverUnsecureChannel(ctx);
+
+        // If DENIED response wasn't sent already, then it's time to check ACL.
+        if(false == ctx->responseSent)
+        {
+#ifdef MULTIPLE_OWNER // TODO Samsung: please verify that these two calls belong
+                      // here inside this conditional statement.
+            // In case of ACL and CRED, The payload required to verify the payload.
+            // Payload information will be used for subowner's permission verification.
+            ctx->payload = (uint8_t*)requestInfo->info.payload;
+            ctx->payloadSize = requestInfo->info.payloadSize;
+#endif //MULTIPLE_OWNER
+
+            OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
+                ctx->requestInfo->info.resourceUri, ctx->requestInfo->method);
+            CheckPermission(ctx);
+            OIC_LOG_V(DEBUG, TAG, "Request for permission %d received responseVal %d.",
+                ctx->requestedPermission, ctx->responseVal);
+
+            // Now that we have determined the correct response and set responseVal,
+            // we generate and send the response to the requester.
+            SRMGenerateResponse(ctx);
+        }
     }
 
-    if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
+    if(false == ctx->responseSent)
     {
-        OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
+        OIC_LOG(ERROR, TAG, "Exiting SRM without responding to requester!");
     }
+
     return;
-exit:
-    responseInfo.result = CA_INTERNAL_SERVER_ERROR;
-    if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
-    {
-        OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
-    }
 }
 
 /**
@@ -325,7 +358,7 @@ void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *re
 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
 {
     OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
-            errorInfo->result, errorInfo->info.resourceUri);
+        errorInfo->result, errorInfo->info.resourceUri);
     if (gErrorHandler)
     {
         gErrorHandler(endPoint, errorInfo);
@@ -333,8 +366,7 @@ void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInf
 }
 
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
-                                 CAResponseCallback respHandler,
-                                 CAErrorCallback errHandler)
+    CAResponseCallback respHandler, CAErrorCallback errHandler)
 {
     OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
     if( !reqHandler || !respHandler || !errHandler)
@@ -389,16 +421,6 @@ void SRMDeInitSecureResources()
     DestroySecureResources();
 }
 
-OCStackResult SRMInitPolicyEngine()
-{
-    return InitPolicyEngine(&g_policyEngineContext);
-}
-
-void SRMDeInitPolicyEngine()
-{
-    DeInitPolicyEngine(&g_policyEngineContext);
-}
-
 bool SRMIsSecurityResourceURI(const char* uri)
 {
     if (!uri)
index 3834b8a..c973ffd 100644 (file)
@@ -36,7 +36,7 @@ extern "C" {
 #include "doxmresource.h"
 
 // test parameters
-PEContext_t g_peContext;
+// PEContext_t g_peContext;
 
 #ifdef __cplusplus
 }
@@ -50,68 +50,72 @@ char g_resource2[] = "Resource2";
 
 extern OicSecDoxm_t *gDoxm;
 
+// These tests need to be rewritten; they do not cover internal ACE/request
+// logic.
+// See JIRA 1787 (https://jira.iotivity.org/browse/IOT-1787)
+
 //Policy Engine Core Tests
-TEST(PolicyEngineCore, InitPolicyEngine)
-{
-    EXPECT_EQ(OC_STACK_OK, InitPolicyEngine(&g_peContext));
-}
+// TEST(PolicyEngineCore, InitPolicyEngine)
+// {
+//     EXPECT_EQ(OC_STACK_OK, InitPolicyEngine(&g_peContext));
+// }
 
 // TODO - in order to unittest this we need InitDoxmResource() to put doxm
 // into Owned state with a known owner.  This will have to be done post v1.1.
-TEST(PolicyEngineCore, CheckPermissionNoAcls)
-{
-    if(OC_STACK_OK == InitDoxmResource())
-    {
-        EXPECT_EQ(ACCESS_DENIED_SUBJECT_NOT_FOUND,
-            CheckPermission(&g_peContext,
-                            &g_subjectIdA,
-                            g_resource1,
-                            PERMISSION_READ));
-    }
-    else
-    {
-        printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
-            PE_UT_TAG);
-    }
-}
+// TEST(PolicyEngineCore, CheckPermissionNoAcls)
+// {
+//     if(OC_STACK_OK == InitDoxmResource())
+//     {
+//         EXPECT_EQ(ACCESS_DENIED_SUBJECT_NOT_FOUND,
+//             CheckPermission(&g_peContext,
+//                             &g_subjectIdA,
+//                             g_resource1,
+//                             PERMISSION_READ));
+//     }
+//     else
+//     {
+//         printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
+//             PE_UT_TAG);
+//     }
+// }
 
-// TODO - in order to unittest this we need InitDoxmResource() to put doxm
-// into Owned state with a known owner.  This will have to be done post v1.1.
-TEST(PolicyEngineCore, CheckDevOwnerRequest)
-{
-    if(OC_STACK_OK == InitDoxmResource())
-    {
-        if(OC_STACK_OK == GetDoxmDevOwnerId(&g_devOwner))
-        {
-            printf("%s", PE_UT_TAG);
-            for(int i = 0; i < UUID_LENGTH; i++)
-            {
-                printf("%d", g_devOwner.id[i]);
-            }
-            printf("\n");
-                EXPECT_EQ(ACCESS_GRANTED,
-                    CheckPermission(&g_peContext,
-                        &g_devOwner,
-                        g_resource1,
-                        PERMISSION_FULL_CONTROL));
-        }
-        else
-        {
-            printf("%s WARNING: GetDoxmDevOwnerId() returned ERROR!\n", \
-                PE_UT_TAG);
-        }
-    }
-    else
-    {
-        printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
-                PE_UT_TAG);
-    }
-}
+// // TODO - in order to unittest this we need InitDoxmResource() to put doxm
+// // into Owned state with a known owner.  This will have to be done post v1.1.
+// TEST(PolicyEngineCore, CheckDevOwnerRequest)
+// {
+//     if(OC_STACK_OK == InitDoxmResource())
+//     {
+//         if(OC_STACK_OK == GetDoxmDevOwnerId(&g_devOwner))
+//         {
+//             printf("%s", PE_UT_TAG);
+//             for(int i = 0; i < UUID_LENGTH; i++)
+//             {
+//                 printf("%d", g_devOwner.id[i]);
+//             }
+//             printf("\n");
+//                 EXPECT_EQ(ACCESS_GRANTED,
+//                     CheckPermission(&g_peContext,
+//                         &g_devOwner,
+//                         g_resource1,
+//                         PERMISSION_FULL_CONTROL));
+//         }
+//         else
+//         {
+//             printf("%s WARNING: GetDoxmDevOwnerId() returned ERROR!\n", \
+//                 PE_UT_TAG);
+//         }
+//     }
+//     else
+//     {
+//         printf("%s WARNING: InitDoxmResource() returned ERROR!\n", \
+//                 PE_UT_TAG);
+//     }
+// }
 
-TEST(PolicyEngineCore, DeInitPolicyEngine)
-{
-    DeInitPolicyEngine(&g_peContext);
-    EXPECT_EQ(STOPPED, g_peContext.state);
-    EXPECT_EQ((uint16_t)0, g_peContext.permission);
-    EXPECT_EQ(ACCESS_DENIED_POLICY_ENGINE_ERROR, g_peContext.retVal);
-}
+// TEST(PolicyEngineCore, DeInitPolicyEngine)
+// {
+//     DeInitPolicyEngine(&g_peContext);
+//     EXPECT_EQ(STOPPED, g_peContext.state);
+//     EXPECT_EQ((uint16_t)0, g_peContext.permission);
+//     EXPECT_EQ(ACCESS_DENIED_POLICY_ENGINE_ERROR, g_peContext.retVal);
+// }
index 5a1f243..73266c1 100644 (file)
@@ -2402,12 +2402,6 @@ OCStackResult OCInit2(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
         result = initResources();
     }
 
-    // Initialize the SRM Policy Engine
-    if(result == OC_STACK_OK)
-    {
-        result = SRMInitPolicyEngine();
-        // TODO after BeachHead delivery: consolidate into single SRMInit()
-    }
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     RMSetStackMode(mode);
 #ifdef ROUTING_GATEWAY
@@ -2493,10 +2487,6 @@ OCStackResult OCStop()
     // Terminate connectivity-abstraction layer.
     CATerminate();
 
-    // De-init the SRM Policy Engine
-    // TODO after BeachHead delivery: consolidate into single SRMDeInit()
-    SRMDeInitPolicyEngine();
-
     stackState = OC_STACK_UNINITIALIZED;
     return OC_STACK_OK;
 }