EMPTY ACK/RESET message Handling by Routing Manager
authorvimala.v <vimala.v@samsung.com>
Mon, 8 Feb 2016 11:11:30 +0000 (16:41 +0530)
committerJon A. Cruz <jonc@osg.samsung.com>
Tue, 23 Feb 2016 08:31:29 +0000 (08:31 +0000)
In case of EMPTY message, according to CoAP spec it can have only 4 bytes containing
Version, Message type, Token Length as 0, Response result as CA_EMPTY and
Message ID.  However Route Option is required for routing the message via multihop.
In order to resolve this issue, we defined a MSGType in the RouteOption which is set
to 0 for normal messages while ACK for Empty acknowledgement and RST for Empty
Reset messages.
When a client sends Empty acknowledgement for a Response received, a POST message
carries the MSGType via multiple hops and the border gateway translates it to Empty ACK

Change-Id: I9550d1ad76f4b6a83a90ee2f06cef1899a3e7564
Signed-off-by: vimala.v <vimala.v@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/4649
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Jon A. Cruz <jonc@osg.samsung.com>
resource/csdk/routing/include/routingmanager.h
resource/csdk/routing/include/routingutility.h
resource/csdk/routing/src/routingmanager.c
resource/csdk/routing/src/routingutility.c
resource/csdk/stack/include/octypes.h
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c

index 3cd6156ddd477cf4af54bd58658ff2c84cfa1387..2dcbd0869569f2097163d0ae7837b56ac3c34321 100644 (file)
@@ -95,14 +95,16 @@ uint16_t RMGetMcastSeqNumber();
  * On reception of request from CA, RI sends to this function.
  * This checks if the route option is present and adds routing information to
  * to the route option data.
- * @param[in,out]   message      Received coap packet.
+ * @param[in,out]  message       Received coap packet.
  * @param[in]      sender        RemoteEndpoint which sent the packet.
  * @param[out]     destination   Populated by RM by parsing message, CA then forwards packet to
  *                               "destination".
+ * @param[out]     isEmptyMsg    Populated by RM by parsing the RouteOption.  If the MSGType is ACK
+ *                               in route option and is for self, then this flag is set.
  * @return  ::CA_STATUS_OK or Appropriate error code.
  */
 OCStackResult RMHandleRequest(CARequestInfo_t *message, const CAEndpoint_t *sender,
-                              bool *selfDestination);
+                              bool *selfDestination, bool *isEmptyMsg);
 
 /**
  * On reception of response from CA, RI sends to this function.
index 3e053416f4a661f3bbdec91702ea2745f431a570..69b9258a4f70d4dce2fbbd348476046c22881ab0 100644 (file)
@@ -85,28 +85,48 @@ extern "C"
             {OC_LOG_V(ERROR, TAG, "%s failed!!", #op); goto exit;} }
 
 /**
- * This structure is used to hold the hopcount, source and destination address.
+ * Message types in RouteOption to differentiate a normal response and Empty response.
+ */
+typedef enum
+{
+   NOR = 0,  /**< Normal Message. */
+   ACK,      /**< Empty Acknowledgement message. */
+   RST,      /**< Empty Reset message. */
+   UNDEFINED /**< Message type not defined. */
+}MSGType;
+
+/**
+ * This structure is used to hold the source address, destination address, message type and
+ * sequence number. This collectively forms the value of Route option in the message.
  */
 typedef struct
 {
     uint32_t srcGw;               /**< Source gateway for this packet. */
     uint32_t destGw;              /**< Destination gateway for this packet. */
-    uint16_t mSeqNum;             /**< HopCount. */
+    uint16_t mSeqNum;             /**< Multicast sequence Number. */
     uint16_t srcEp;               /**< Source endpoint for this packet. */
     uint16_t destEp;              /**< Destination endpoint for this packet. */
+    uint8_t msgType;              /**< Type of Message: Empty or normal. */
 } RMRouteOption_t;
 
+/**
+ * To set the stack mode in Routing manager.
+ */
+void RMSetStackMode(OCMode mode);
+
 /**
  * Adds the destination address to the Route options.
  * If Route option is already present, it adds the destination address information to
  * Route option else creates a new Route option with the destination address info.
  * @param[in]       endpoint        Destination address.
- * @param[in,out]   options         Header options present in the Request/response message.
- * @param[in,out]   numOptions      Number of options present in the message.
+ * @param[in,out]   message         Request/response message to add the route option
+ * @param[in]       isRequest       True if message is request else false.
+ * @param[out]      doPost          True if a POST message be sent for empty packet to
+ *                                  Routing gateway.
  * @return  ::CA_STATUS_OK or Appropriate error code.
  */
-OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
-                        uint8_t *numOptions);
+OCStackResult RMAddInfo(const char *destination, void *message, bool isRequest,
+                        bool *doPost);
 
 /**
  * Removes the Route Option from the header options.
index bf8215311d5e54520d2b899827669d428b49c531..5f1aff6341aa76660ff95586ba9ce517b3b64331 100644 (file)
@@ -906,13 +906,14 @@ uint16_t RMGetMcastSeqNumber()
  */
 
 OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *sender,
-                             bool *selfDestination)
+                             bool *selfDestination, bool *isEmptyMsg)
 {
     RM_NULL_CHECK_WITH_RET(message, RM_TAG, "message");
     RM_NULL_CHECK_WITH_RET(sender, RM_TAG, "sender");
     RM_NULL_CHECK_WITH_RET(selfDestination, RM_TAG, "selfDestination");
 
     bool forward = false;
+    bool isEMPTYPacket = false;
     CAEndpoint_t nextHop = {.adapter = CA_DEFAULT_ADAPTER};
     CAInfo_t *info = NULL;
     if (isRequest)
@@ -1048,6 +1049,13 @@ OCStackResult RMHandlePacket(bool isRequest, void *message, const CAEndpoint_t *
     else if (g_GatewayID == routeOption.destGw)
     {
         OIC_LOG(INFO, RM_TAG, "GatewayId found in destination");
+
+        // Check the MSGType of RouteOption to find if the packet is EMPTY packet.
+        if (ACK == routeOption.msgType || RST == routeOption.msgType)
+        {
+            isEMPTYPacket = true;
+        }
+
         /*
          * This unicast packet either belongs to us or any of our connected end devices
          * check if packet belongs to end device.
@@ -1111,7 +1119,8 @@ rewriteandexit:
     if (forward)
     {
         // Don't forward any packet meant for gateway resource.
-        if (info->resourceUri && (0 == strcmp(info->resourceUri, OC_RSRVD_GATEWAY_URI)))
+        if (info->resourceUri && (0 == strcmp(info->resourceUri, OC_RSRVD_GATEWAY_URI)) &&
+            (ACK != routeOption.msgType))
         {
             OIC_LOG(ERROR, RM_TAG, "Not forwarding gateway resource packet");
         }
@@ -1120,6 +1129,30 @@ rewriteandexit:
             OIC_LOG(ERROR, RM_TAG, "This is secured request. Not supported by routing manager");
             return OC_STACK_ERROR;
         }
+        else if (isEMPTYPacket)
+        {
+            OC_LOG(DEBUG, TAG, "The message to be Forwarded is a EMPTY message");
+            CAResponseInfo_t responseMessage = {.result = CA_EMPTY};
+            if (ACK == routeOption.msgType)
+            {
+                responseMessage.info.type = CA_MSG_ACKNOWLEDGE;
+            }
+            else
+            {
+                responseMessage.info.type = CA_MSG_RESET;
+            }
+
+            responseMessage.info.messageId = info->messageId;
+
+            CAResult_t caRes = CASendResponse(&nextHop, &responseMessage);
+            if (CA_STATUS_OK != caRes)
+            {
+                OC_LOG_V(ERROR, RM_TAG, "Failed to forward response to next hop [%d][%s]",
+                         caRes, nextHop.addr);
+                // Since a response is always unicast, return error here.
+                return OC_STACK_ERROR;
+            }
+        }
         else
         {
             // rewrite any changes in routing option.
@@ -1167,13 +1200,44 @@ rewriteandexit:
             }
         }
     }
+    else
+    {
+        if (isEMPTYPacket)
+        {
+            if (isRequest)
+            {
+                OC_LOG(DEBUG, TAG, "POST message with type ACK in Route Option");
+                if (NULL != isEmptyMsg)
+                {
+                    *isEmptyMsg = true;
+                }
+            }
+            else
+            {
+                OC_LOG(DEBUG, TAG, "Response for EMPTY message is received");
+                CAResponseInfo_t *msg = message;
+                if (ACK == (MSGType)routeOption.msgType)
+                {
+                    msg->info.type = CA_MSG_ACKNOWLEDGE;
+                }
+                else
+                {
+                    msg->info.type = CA_MSG_RESET;
+                }
+                msg->result = CA_EMPTY;
+                OICFree(msg->info.token);
+                msg->info.token = NULL;
+                msg->info.tokenLength = 0;
+            }
+        }
+    }
 
     OIC_LOG_V(INFO, RM_TAG, "Sender: [%u] Destination: [%u]", routeOption.srcGw, routeOption.destGw);
     return OC_STACK_OK;
 }
 
 OCStackResult RMHandleRequest(CARequestInfo_t *message, const CAEndpoint_t *sender,
-                              bool *selfDestination)
+                              bool *selfDestination, bool *isEmptyMsg)
 {
     if (!g_isRMInitialized)
     {
@@ -1181,7 +1245,7 @@ OCStackResult RMHandleRequest(CARequestInfo_t *message, const CAEndpoint_t *send
         *selfDestination = true;
         return OC_STACK_OK;
     }
-    OCStackResult res = RMHandlePacket(true, message, sender, selfDestination);
+    OCStackResult res = RMHandlePacket(true, message, sender, selfDestination, isEmptyMsg);
     return res;
 }
 
@@ -1194,6 +1258,6 @@ OCStackResult RMHandleResponse(CAResponseInfo_t *message, const CAEndpoint_t *se
         *selfDestination = true;
         return OC_STACK_OK;
     }
-    OCStackResult res = RMHandlePacket(false, message, sender, selfDestination);
+    OCStackResult res = RMHandlePacket(false, message, sender, selfDestination, NULL);
     return res;
 }
index ca4850e70b2307c5f0214c53c64ec447caf9475b..82acf241e0da677ff26ff4bda96cc0ad60621a60 100644 (file)
 
 /**
  * Minimum routing option data length is
- * length of src address(1byte) + length of destination address(1byte) + hop count(2bytes)
+ * length of src address(1byte) + length of destination address(1byte) +
+ * Seq Num(2bytes) + Msg Type(1 bytes)
  */
-#define MIN_ROUTE_OPTION_LEN 4
+#define MIN_ROUTE_OPTION_LEN 5
+
+/**
+ * Stack mode.
+ */
+static OCMode g_rmStackMode = OC_CLIENT;
+
+void RMSetStackMode(OCMode mode)
+{
+    g_rmStackMode = mode;
+}
 
 // destination and source are <GatewayId><ClientId> here, where ClientId is optional.
-OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
-                        uint8_t *numOptions)
+OCStackResult RMAddInfo(const char *destination, void *message, bool isRequest,
+                        bool *doPost)
 {
     OIC_LOG(DEBUG, TAG, "IN");
-    RM_NULL_CHECK_WITH_RET(options, TAG, "options");
-    RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
+    RM_NULL_CHECK_WITH_RET(message, TAG, "options");
+
+    CAHeaderOption_t **options = NULL;
+    uint8_t *numOptions = NULL;
+
+    if (isRequest)
+    {
+        CARequestInfo_t *requestMsg = message;
+        options = &(requestMsg->info.options);
+        RM_NULL_CHECK_WITH_RET(options, TAG, "options");
+        numOptions = &(requestMsg->info.numOptions);
+        RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
+    }
+    else
+    {
+        CAResponseInfo_t *respMsg = message;
+        if ('\0' == destination[0] && (CA_EMPTY == respMsg->result))
+        {
+            OC_LOG(DEBUG, TAG, "Response is for an Endpoint, No need to add the routing Option");
+            return OC_STACK_OK;
+        }
+        options = &(respMsg->info.options);
+        RM_NULL_CHECK_WITH_RET(options, TAG, "options");
+        numOptions = &(respMsg->info.numOptions);
+        RM_NULL_CHECK_WITH_RET(numOptions, TAG, "numOptions");
+    }
+
 
     CAHeaderOption_t *optionPtr = NULL;
     int8_t index = -1;
@@ -86,6 +122,38 @@ OCStackResult RMAddInfo(const char *destination, CAHeaderOption_t **options,
         }
     }
 
+    if (!isRequest)
+    {
+        CAResponseInfo_t *respMsg = message;
+        if (CA_EMPTY == respMsg->result && CA_MSG_ACKNOWLEDGE == respMsg->info.type)
+        {
+            OC_LOG(DEBUG, TAG, "CA_EMPTY WITH ACKNOWLEDGEMENT");
+            routeOption.msgType = ACK;
+            if (OC_SERVER == g_rmStackMode)
+            {
+                OC_LOG(DEBUG, TAG, "This is server mode");
+                // Send the Empty message in the response with adding the MSGType in Route option.
+                respMsg->info.type = CA_MSG_NONCONFIRM;
+                respMsg->result = CA_CONTENT;
+            }
+            else
+            {
+                OC_LOG(DEBUG, TAG, "Send a POST request");
+                if (NULL != doPost)
+                {
+                    *doPost = true;
+                }
+            }
+        }
+        else if (CA_EMPTY == respMsg->result && CA_MSG_RESET == respMsg->info.type)
+        {
+            OC_LOG(DEBUG, TAG, "CA_EMPTY WITH RESET");
+            routeOption.msgType = RST;
+            respMsg->info.type = CA_MSG_NONCONFIRM;
+            respMsg->result = CA_CONTENT;
+        }
+    }
+
     if(destination)
     {
         memcpy(&(routeOption.destGw), destination, sizeof(routeOption.destGw));
@@ -268,6 +336,8 @@ OCStackResult RMCreateRouteOption(const RMRouteOption_t *optValue, CAHeaderOptio
     }
 
     memcpy(tempData + count, &optValue->mSeqNum, sizeof(optValue->mSeqNum));
+    count += sizeof(optValue->mSeqNum);
+    memcpy(tempData + count, &optValue->msgType, sizeof(optValue->msgType));
     memcpy(options->optionData, tempData, totalLength);
 
     options->optionID = RM_OPTION_MESSAGE_SWITCHING;
@@ -321,10 +391,13 @@ OCStackResult RMParseRouteOption(const CAHeaderOption_t *options, RMRouteOption_
         }
     }
     memcpy(&optValue->mSeqNum, options->optionData + count, sizeof(optValue->mSeqNum));
+    count += sizeof(optValue->mSeqNum);
+    memcpy(&optValue->msgType, options->optionData + count, sizeof(optValue->msgType));
 
     OIC_LOG_V(INFO, RM_TAG, "Option hopcount is %d", optValue->mSeqNum);
     OIC_LOG_V(INFO, RM_TAG, "Option Sender Addr is [%u][%u]", optValue->srcGw, optValue->srcEp);
     OIC_LOG_V(INFO, RM_TAG, "Option Dest Addr is [%u][%u]", optValue->destGw, optValue->destEp);
+    OIC_LOG_V(INFO, RM_TAG, "Message Type is [%u]", optValue->msgType);
     OIC_LOG(DEBUG, RM_TAG, "OUT");
     return OC_STACK_OK;
 }
index 0a90849e30dbf4ed40e54e4761b3a5d29c2cb110..3159bd8ea3ce2b359a1e783c22cb7cc311ca52cd 100644 (file)
@@ -64,7 +64,7 @@ extern "C" {
 
 /** Resource Type.*/
 #define OC_RSRVD_RESOURCE_TYPES_URI           "/oic/res/types/d"
-#ifdef ROUTING_GATEWAY
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
 /** Gateway URI.*/
 #define OC_RSRVD_GATEWAY_URI                  "/oic/gateway"
 #endif
index 618bcaf2460098d6075dac3df683b7dfb1969be9..1601a9ca911e76fe712ab2aaa3a0218f86bd294f 100644 (file)
@@ -157,8 +157,7 @@ static OCStackResult OCSendResponse(const CAEndpoint_t *object, CAResponseInfo_t
 {
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     // Add route info in RM option.
-    OCStackResult rmResult = RMAddInfo(object->routeData, &(responseInfo->info.options),
-                       &(responseInfo->info.numOptions));
+    OCStackResult rmResult = RMAddInfo(object->routeData, responseInfo, false, NULL);
     if(OC_STACK_OK != rmResult)
     {
         OIC_LOG(ERROR, TAG, "Add option failed");
index 5082995b8fb8e7ac9b2a6704d6bc7c1b1f7e76ab..afc34fb96bdc3578745778d831a2c3658aba0653 100644 (file)
@@ -466,8 +466,7 @@ static OCStackResult OCSendRequest(const CAEndpoint_t *object, CARequestInfo_t *
     VERIFY_NON_NULL(requestInfo, FATAL, OC_STACK_INVALID_PARAM);
 
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-    OCStackResult rmResult = RMAddInfo(object->routeData, &(requestInfo->info.options),
-                                     &(requestInfo->info.numOptions));
+    OCStackResult rmResult = RMAddInfo(object->routeData, requestInfo, true, NULL);
     if (OC_STACK_OK != rmResult)
     {
         OIC_LOG(ERROR, TAG, "Add destination option failed");
@@ -1059,40 +1058,9 @@ exit:
     return result;
 }
 
-void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+void OCHandleResponse(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
 {
-    VERIFY_NON_NULL_NR(endPoint, FATAL);
-    VERIFY_NON_NULL_NR(responseInfo, FATAL);
-
-    OIC_LOG(INFO, TAG, "Enter HandleCAResponses");
-
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-#ifdef ROUTING_GATEWAY
-    bool needRIHandling = false;
-    /*
-     * Routing manager is going to update either of endpoint or response or both.
-     * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
-     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
-     * destination.
-     */
-    OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
-                                         &needRIHandling);
-    if(ret != OC_STACK_OK || !needRIHandling)
-    {
-        OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
-        return;
-    }
-#endif
-
-    /*
-     * Put source in sender endpoint so that the next packet from application can be routed to
-     * proper destination and remove "RM" coap header option before passing request / response to
-     * RI as this option will make no sense to either RI or application.
-     */
-    RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
-                 (uint8_t *) &(responseInfo->info.numOptions),
-                 (CAEndpoint_t *) endPoint);
-#endif
+    OC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
 
     if(responseInfo->info.resourceUri &&
         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
@@ -1391,6 +1359,46 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
     OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
 }
 
+void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* responseInfo)
+{
+    VERIFY_NON_NULL_NR(endPoint, FATAL);
+    VERIFY_NON_NULL_NR(responseInfo, FATAL);
+
+    OC_LOG(INFO, TAG, "Enter HandleCAResponses");
+
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+#ifdef ROUTING_GATEWAY
+    bool needRIHandling = false;
+    /*
+     * Routing manager is going to update either of endpoint or response or both.
+     * This typecasting is done to avoid unnecessary duplication of Endpoint and responseInfo
+     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
+     * destination.
+     */
+    OCStackResult ret = RMHandleResponse((CAResponseInfo_t *)responseInfo, (CAEndpoint_t *)endPoint,
+                                         &needRIHandling);
+    if(ret != OC_STACK_OK || !needRIHandling)
+    {
+        OC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
+        return;
+    }
+#endif
+
+    /*
+     * Put source in sender endpoint so that the next packet from application can be routed to
+     * proper destination and remove "RM" coap header option before passing request / response to
+     * RI as this option will make no sense to either RI or application.
+     */
+    RMUpdateInfo((CAHeaderOption_t **) &(responseInfo->info.options),
+                 (uint8_t *) &(responseInfo->info.numOptions),
+                 (CAEndpoint_t *) endPoint);
+#endif
+
+    OCHandleResponse(endPoint, responseInfo);
+
+    OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
+}
+
 /*
  * This function handles error response from CA
  * code shall be added to handle the errors
@@ -1423,6 +1431,7 @@ OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16
         const uint8_t numOptions, const CAHeaderOption_t *options,
         CAToken_t token, uint8_t tokenLength, const char *resourceUri)
 {
+    OIC_LOG(DEBUG, TAG, "Entering SendDirectStackResponse");
     CAResponseInfo_t respInfo = {
         .result = responseResult
     };
@@ -1447,73 +1456,139 @@ OCStackResult SendDirectStackResponse(const CAEndpoint_t* endPoint, const uint16
 
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     // Add the destination to route option from the endpoint->routeData.
-    OCStackResult result = RMAddInfo(endPoint->routeData,
-                                     &(respInfo.info.options),
-                                     &(respInfo.info.numOptions));
+    bool doPost = false;
+    OCStackResult result = RMAddInfo(endPoint->routeData, &respInfo, false, &doPost);
     if(OC_STACK_OK != result)
     {
         OIC_LOG_V(ERROR, TAG, "Add routing option failed [%d]", result);
         return result;
     }
-#endif
-
-    CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+    if (doPost)
+    {
+        OC_LOG(DEBUG, TAG, "Sending a POST message for EMPTY ACK in Client Mode");
+        CARequestInfo_t reqInfo = {.method = CA_POST };
+        /* The following initialization is not done in a single initializer block as in
+         * arduino, .c file is compiled as .cpp and moves it from C99 to C++11.  The latter
+         * does not have designated initalizers. This is a work-around for now.
+         */
+        reqInfo.info.type = CA_MSG_NONCONFIRM;
+        reqInfo.info.messageId = coapID;
+        reqInfo.info.tokenLength = tokenLength;
+        reqInfo.info.token = token;
+        reqInfo.info.numOptions = respInfo.info.numOptions;
+        reqInfo.info.payload = NULL;
+        reqInfo.info.resourceUri = OICStrdup (OC_RSRVD_GATEWAY_URI);
+        if (reqInfo.info.numOptions)
+        {
+            reqInfo.info.options =
+                (CAHeaderOption_t *)OICCalloc(reqInfo.info.numOptions, sizeof(CAHeaderOption_t));
+            if (NULL == reqInfo.info.options)
+            {
+                OC_LOG(ERROR, TAG, "Calloc failed");
+                return OC_STACK_NO_MEMORY;
+            }
+            memcpy (reqInfo.info.options, respInfo.info.options,
+                    sizeof(CAHeaderOption_t) * reqInfo.info.numOptions);
 
-    // resourceUri in the info field is cloned in the CA layer and
-    // thus ownership is still here.
-    OICFree (respInfo.info.resourceUri);
-    OICFree (respInfo.info.options);
-    if(CA_STATUS_OK != caResult)
+        }
+        CAResult_t caResult = CASendRequest(endPoint, &reqInfo);
+        OICFree (reqInfo.info.resourceUri);
+        OICFree (reqInfo.info.options);
+        OICFree (respInfo.info.resourceUri);
+        OICFree (respInfo.info.options);
+        if (CA_STATUS_OK != caResult)
+        {
+            OC_LOG(ERROR, TAG, "CASendRequest error");
+            return CAResultToOCResult(caResult);
+        }
+    }
+    else
+#endif
     {
-        OIC_LOG(ERROR, TAG, "CASendResponse error");
-        return CAResultToOCResult(caResult);
+        CAResult_t caResult = CASendResponse(endPoint, &respInfo);
+
+        // resourceUri in the info field is cloned in the CA layer and
+        // thus ownership is still here.
+        OICFree (respInfo.info.resourceUri);
+        OICFree (respInfo.info.options);
+        if(CA_STATUS_OK != caResult)
+        {
+            OIC_LOG(ERROR, TAG, "CASendResponse error");
+            return CAResultToOCResult(caResult);
+        }
     }
+    OC_LOG(DEBUG, TAG, "Exit SendDirectStackResponse");
     return OC_STACK_OK;
 }
 
-//This function will be called back by CA layer when a request is received
-void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
 {
-    OIC_LOG(INFO, TAG, "Enter HandleCARequests");
-    if(!endPoint)
+    OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
+    OCStackResult result = OC_STACK_ERROR;
+    if(!protocolRequest)
     {
-        OIC_LOG(ERROR, TAG, "endPoint is NULL");
-        return;
+        OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
+        return OC_STACK_INVALID_PARAM;
     }
 
-    if(!requestInfo)
+    OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
+            protocolRequest->tokenLength);
+    if(!request)
     {
-        OIC_LOG(ERROR, TAG, "requestInfo is NULL");
-        return;
+        OIC_LOG(INFO, TAG, "This is a new Server Request");
+        result = AddServerRequest(&request, protocolRequest->coapID,
+                protocolRequest->delayedResNeeded, 0, protocolRequest->method,
+                protocolRequest->numRcvdVendorSpecificHeaderOptions,
+                protocolRequest->observationOption, protocolRequest->qos,
+                protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
+                protocolRequest->payload, protocolRequest->requestToken,
+                protocolRequest->tokenLength, protocolRequest->resourceUrl,
+                protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
+                &protocolRequest->devAddr);
+        if (OC_STACK_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "Error adding server request");
+            return result;
+        }
+
+        if(!request)
+        {
+            OIC_LOG(ERROR, TAG, "Out of Memory");
+            return OC_STACK_NO_MEMORY;
+        }
+
+        if(!protocolRequest->reqMorePacket)
+        {
+            request->requestComplete = 1;
+        }
+    }
+    else
+    {
+        OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
     }
 
-#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
-#ifdef ROUTING_GATEWAY
-    bool needRIHandling = false;
-    /*
-     * Routing manager is going to update either of endpoint or request or both.
-     * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
-     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
-     * destination. It can also remove "RM" coap header option before passing request / response to
-     * RI as this option will make no sense to either RI or application.
-     */
-    OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
-                                     &needRIHandling);
-    if(OC_STACK_OK != ret || !needRIHandling)
+    if(request->requestComplete)
     {
-        OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
-        return;
+        OIC_LOG(INFO, TAG, "This Server Request is complete");
+        ResourceHandling resHandling = OC_RESOURCE_VIRTUAL;
+        OCResource *resource = NULL;
+        result = DetermineResourceHandling (request, &resHandling, &resource);
+        if (result == OC_STACK_OK)
+        {
+            result = ProcessRequest(resHandling, resource, request);
+        }
     }
-#endif
+    else
+    {
+        OIC_LOG(INFO, TAG, "This Server Request is incomplete");
+        result = OC_STACK_CONTINUE;
+    }
+    return result;
+}
 
-    /*
-     * Put source in sender endpoint so that the next packet from application can be routed to
-     * proper destination and remove RM header option.
-     */
-    RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
-                 (uint8_t *) &(requestInfo->info.numOptions),
-                 (CAEndpoint_t *) endPoint);
-#endif
+void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+{
+    OC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
 
 #ifdef TCP_ADAPTER
     if (requestInfo->info.resourceUri &&
@@ -1714,72 +1789,76 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     // The token is copied in there, and is thus still owned by this function.
     OICFree(serverRequest.payload);
     OICFree(serverRequest.requestToken);
-    OIC_LOG(INFO, TAG, "Exit HandleCARequests");
+    OIC_LOG(INFO, TAG, "Exit OCHandleRequests");
 }
 
-OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
+//This function will be called back by CA layer when a request is received
+void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
 {
-    OIC_LOG(INFO, TAG, "Entering HandleStackRequests (OCStack Layer)");
-    OCStackResult result = OC_STACK_ERROR;
-    ResourceHandling resHandling;
-    OCResource *resource;
-    if(!protocolRequest)
+    OIC_LOG(INFO, TAG, "Enter HandleCARequests");
+    if(!endPoint)
     {
-        OIC_LOG(ERROR, TAG, "protocolRequest is NULL");
-        return OC_STACK_INVALID_PARAM;
+        OIC_LOG(ERROR, TAG, "endPoint is NULL");
+        return;
     }
 
-    OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken,
-            protocolRequest->tokenLength);
-    if(!request)
+    if(!requestInfo)
     {
-        OIC_LOG(INFO, TAG, "This is a new Server Request");
-        result = AddServerRequest(&request, protocolRequest->coapID,
-                protocolRequest->delayedResNeeded, 0, protocolRequest->method,
-                protocolRequest->numRcvdVendorSpecificHeaderOptions,
-                protocolRequest->observationOption, protocolRequest->qos,
-                protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions,
-                protocolRequest->payload, protocolRequest->requestToken,
-                protocolRequest->tokenLength, protocolRequest->resourceUrl,
-                protocolRequest->reqTotalSize, protocolRequest->acceptFormat,
-                &protocolRequest->devAddr);
-        if (OC_STACK_OK != result)
-        {
-            OIC_LOG(ERROR, TAG, "Error adding server request");
-            return result;
-        }
-
-        if(!request)
-        {
-            OIC_LOG(ERROR, TAG, "Out of Memory");
-            return OC_STACK_NO_MEMORY;
-        }
-
-        if(!protocolRequest->reqMorePacket)
-        {
-            request->requestComplete = 1;
-        }
+        OIC_LOG(ERROR, TAG, "requestInfo is NULL");
+        return;
     }
-    else
+
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+#ifdef ROUTING_GATEWAY
+    bool needRIHandling = false;
+    bool isEmptyMsg = false;
+    /*
+     * Routing manager is going to update either of endpoint or request or both.
+     * This typecasting is done to avoid unnecessary duplication of Endpoint and requestInfo
+     * RM can update "routeData" option in endPoint so that future RI requests can be sent to proper
+     * destination. It can also remove "RM" coap header option before passing request / response to
+     * RI as this option will make no sense to either RI or application.
+     */
+    OCStackResult ret = RMHandleRequest((CARequestInfo_t *)requestInfo, (CAEndpoint_t *)endPoint,
+                                        &needRIHandling, &isEmptyMsg);
+    if(OC_STACK_OK != ret || !needRIHandling)
     {
-        OIC_LOG(INFO, TAG, "This is either a repeated or blocked Server Request");
+        OIC_LOG_V(INFO, TAG, "Routing status![%d]. Not forwarding to RI", ret);
+        return;
     }
+#endif
 
-    if(request->requestComplete)
-    {
-        OIC_LOG(INFO, TAG, "This Server Request is complete");
-        result = DetermineResourceHandling (request, &resHandling, &resource);
-        if (result == OC_STACK_OK)
-        {
-            result = ProcessRequest(resHandling, resource, request);
-        }
+    /*
+     * Put source in sender endpoint so that the next packet from application can be routed to
+     * proper destination and remove RM header option.
+     */
+    RMUpdateInfo((CAHeaderOption_t **) &(requestInfo->info.options),
+                 (uint8_t *) &(requestInfo->info.numOptions),
+                 (CAEndpoint_t *) endPoint);
+
+#ifdef ROUTING_GATEWAY
+    if (isEmptyMsg)
+    {
+        /*
+         * In Gateways, the MSGType in route option is used to check if the actual
+         * response is EMPTY message(4 bytes CoAP Header).  In case of Client, the
+         * EMPTY response is sent in the form of POST request which need to be changed
+         * to a EMPTY response by RM.  This translation is done in this part of the code.
+         */
+        OIC_LOG(INFO, TAG, "This is a Empty response from the Client");
+        CAResponseInfo_t respInfo = {.result = CA_EMPTY,
+                                     .info.messageId = requestInfo->info.messageId,
+                                     .info.type = CA_MSG_ACKNOWLEDGE};
+        OCHandleResponse(endPoint, &respInfo);
     }
     else
+#endif
+#endif
     {
-        OIC_LOG(INFO, TAG, "This Server Request is incomplete");
-        result = OC_STACK_CONTINUE;
+        // Normal handling of the packet
+        OCHandleRequests(endPoint, requestInfo);
     }
-    return result;
+    OIC_LOG(INFO, TAG, "Exit HandleCARequests");
 }
 
 bool validatePlatformInfo(OCPlatformInfo info)
@@ -1959,13 +2038,15 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
         result = SRMInitPolicyEngine();
         // TODO after BeachHead delivery: consolidate into single SRMInit()
     }
-
+#if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
+    RMSetStackMode(mode);
 #ifdef ROUTING_GATEWAY
     if (OC_GATEWAY == myStackMode)
     {
         result = RMInitialize();
     }
 #endif
+#endif
 
 #ifdef TCP_ADAPTER
     if(result == OC_STACK_OK)