Merge branch 'master' into cloud-interface
[platform/upstream/iotivity.git] / resource / csdk / stack / src / ocstack.c
index 992819e..ac14ccd 100644 (file)
 // For POSIX.1-2001 base specification,
 // Refer http://pubs.opengroup.org/onlinepubs/009695399/
 #define _POSIX_C_SOURCE 200112L
+#ifndef __STDC_FORMAT_MACROS
 #define __STDC_FORMAT_MACROS
+#endif
+#ifndef __STDC_LIMIT_MACROS
 #define __STDC_LIMIT_MACROS
+#endif
 #include <inttypes.h>
 #include <string.h>
 #include <ctype.h>
 #endif
 #endif
 
-#ifdef WITH_ARDUINO
+#ifdef TCP_ADAPTER
+#include "oickeepalive.h"
+#endif
+
+//#ifdef DIRECT_PAIRING
+#include "directpairing.h"
+//#endif
+
+#ifdef HAVE_ARDUINO_TIME_H
 #include "Time.h"
-#else
+#endif
+#ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
 #include "coap_time.h"
 #include "utlist.h"
 #include "pdu.h"
 
-#ifndef ARDUINO
+#ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
 #endif
 
@@ -119,6 +132,7 @@ static bool gRASetInfo = false;
 OCDeviceEntityHandler defaultDeviceHandler;
 void* defaultDeviceHandlerCallbackParameter = NULL;
 static const char COAP_TCP[] = "coap+tcp:";
+static const char CORESPEC[] = "core";
 
 //-----------------------------------------------------------------------------
 // Macros
@@ -262,16 +276,6 @@ static void deleteAllResources();
  */
 static void incrementSequenceNumber(OCResource * resPtr);
 
-/**
- * Verify the lengths of the URI and the query separately.
- *
- * @param inputUri Input URI and query.
- * @param uriLen The length of the initial URI with query.
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-static OCStackResult verifyUriQueryLength(const char * inputUri,
-        uint16_t uriLen);
-
 /*
  * Attempts to initialize every network interface that the CA Layer might have compiled in.
  *
@@ -292,12 +296,20 @@ static CAResult_t OCSelectNetwork();
 static uint32_t GetTicks(uint32_t afterMilliSeconds);
 
 /**
+ * Convert CAResult_t to OCStackResult.
+ *
+ * @param caResult CAResult_t code.
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+static OCStackResult CAResultToOCStackResult(CAResult_t caResult);
+
+/**
  * Convert CAResponseResult_t to OCStackResult.
  *
  * @param caCode CAResponseResult_t code.
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-static OCStackResult CAToOCStackResult(CAResponseResult_t caCode);
+static OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode);
 
 /**
  * Convert OCStackResult to CAResponseResult_t.
@@ -426,7 +438,7 @@ void CopyEndpointToDevAddr(const CAEndpoint_t *in, OCDevAddr *out)
     out->flags = CAToOCTransportFlags(in->flags);
     OICStrcpy(out->addr, sizeof(out->addr), in->addr);
     out->port = in->port;
-    out->interface = in->interface;
+    out->ifindex = in->ifindex;
 #if defined (ROUTING_GATEWAY) || defined (ROUTING_EP)
     memcpy(out->routeData, in->routeData, sizeof(out->routeData));
 #endif
@@ -444,7 +456,7 @@ void CopyDevAddrToEndpoint(const OCDevAddr *in, CAEndpoint_t *out)
     memcpy(out->routeData, in->routeData, sizeof(out->routeData));
 #endif
     out->port = in->port;
-    out->interface = in->interface;
+    out->ifindex = in->ifindex;
 }
 
 void FixUpClientResponse(OCClientResponse *cr)
@@ -462,8 +474,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");
@@ -508,7 +519,8 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                                                 NULL, PAYLOAD_TYPE_REPRESENTATION,
                                                 NULL, 0, 0, NULL,
                                                 OC_OBSERVE_DEREGISTER,
-                                                observer->observeId);
+                                                observer->observeId,
+                                                0);
             if(result != OC_STACK_OK)
             {
                 return result;
@@ -559,7 +571,8 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
                                                     NULL, PAYLOAD_TYPE_REPRESENTATION,
                                                     NULL, 0, 0, NULL,
                                                     OC_OBSERVE_DEREGISTER,
-                                                    observer->observeId);
+                                                    observer->observeId,
+                                                    0);
                 if(result != OC_STACK_OK)
                 {
                     return OC_STACK_ERROR;
@@ -594,7 +607,30 @@ OCStackResult OCStackFeedBack(CAToken_t token, uint8_t tokenLength, uint8_t stat
         }
     return result;
 }
-OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
+
+static OCStackResult CAResultToOCStackResult(CAResult_t caResult)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+
+    switch(caResult)
+    {
+        case CA_ADAPTER_NOT_ENABLED:
+        case CA_SERVER_NOT_STARTED:
+            ret = OC_STACK_ADAPTER_NOT_ENABLED;
+            break;
+        case CA_MEMORY_ALLOC_FAILED:
+            ret = OC_STACK_NO_MEMORY;
+            break;
+        case CA_STATUS_INVALID_PARAM:
+            ret = OC_STACK_INVALID_PARAM;
+            break;
+        default:
+            break;
+    }
+    return ret;
+}
+
+OCStackResult CAResponseToOCStackResult(CAResponseResult_t caCode)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
@@ -608,6 +644,7 @@ OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
             break;
         case CA_CHANGED:
         case CA_CONTENT:
+        case CA_VALID:
             ret = OC_STACK_OK;
             break;
         case CA_BAD_REQ:
@@ -625,6 +662,9 @@ OCStackResult CAToOCStackResult(CAResponseResult_t caCode)
         case CA_RETRANSMIT_TIMEOUT:
             ret = OC_STACK_COMM_ERROR;
             break;
+        case CA_REQUEST_ENTITY_TOO_LARGE:
+            ret = OC_STACK_TOO_LARGE_REQ;
+            break;
         default:
             break;
     }
@@ -1054,40 +1094,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
+    OIC_LOG(DEBUG, TAG, "Enter OCHandleResponse");
 
     if(responseInfo->info.resourceUri &&
         strcmp(responseInfo->info.resourceUri, OC_RSRVD_PRESENCE_URI) == 0)
@@ -1131,7 +1140,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                                                 sizeof (response.identity.id));
             response.identity.id_length = responseInfo->info.identity.id_length;
 
-            response.result = CAToOCStackResult(responseInfo->result);
+            response.result = CAResponseToOCStackResult(responseInfo->result);
             cbNode->callBack(cbNode->context,
                     cbNode->handle, &response);
             FindAndDeleteClientCB(cbNode);
@@ -1143,7 +1152,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
 
             OCClientResponse response =
                 {.devAddr = {.adapter = OC_DEFAULT_ADAPTER}};
-            response.sequenceNumber = OC_OBSERVE_NO_OPTION;
+            response.sequenceNumber = -1;
             CopyEndpointToDevAddr(endPoint, &response.devAddr);
             FixUpClientResponse(&response);
             response.resourceUri = responseInfo->info.resourceUri;
@@ -1151,7 +1160,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                                                 sizeof (response.identity.id));
             response.identity.id_length = responseInfo->info.identity.id_length;
 
-            response.result = CAToOCStackResult(responseInfo->result);
+            response.result = CAResponseToOCStackResult(responseInfo->result);
 
             if(responseInfo->info.payload &&
                responseInfo->info.payloadSize)
@@ -1187,6 +1196,12 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                     {
                         type = PAYLOAD_TYPE_RD;
                     }
+#ifdef TCP_ADAPTER
+                    else if (strcmp(cbNode->requestUri, KEEPALIVE_RESOURCE_URI) == 0)
+                    {
+                        type = PAYLOAD_TYPE_REPRESENTATION;
+                    }
+#endif
                     else
                     {
                         OIC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
@@ -1202,12 +1217,20 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
                          cbNode->method == OC_REST_DELETE)
                 {
                     char targetUri[MAX_URI_LENGTH];
-                    snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
-                            OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
+                    snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s", OC_RSRVD_RD_URI,
+                            OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
                     if (strcmp(targetUri, cbNode->requestUri) == 0)
                     {
                         type = PAYLOAD_TYPE_RD;
                     }
+                    else if (strcmp(OC_RSRVD_PLATFORM_URI, cbNode->requestUri) == 0)
+                    {
+                        type = PAYLOAD_TYPE_PLATFORM;
+                    }
+                    else if (strcmp(OC_RSRVD_DEVICE_URI, cbNode->requestUri) == 0)
+                    {
+                        type = PAYLOAD_TYPE_DEVICE;
+                    }
                     if (type == PAYLOAD_TYPE_INVALID)
                     {
                         OIC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
@@ -1354,7 +1377,7 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
             {
                 OIC_LOG(INFO, TAG, "Received a message without callbacks. Sending RESET");
                 SendDirectStackResponse(endPoint, responseInfo->info.messageId, CA_EMPTY,
-                        CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
+                                        CA_MSG_RESET, 0, NULL, NULL, 0, NULL);
             }
         }
 
@@ -1377,6 +1400,46 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
         return;
     }
 
+    OIC_LOG(INFO, TAG, "Exit OCHandleResponse");
+}
+
+void HandleCAResponses(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
+
+    OCHandleResponse(endPoint, responseInfo);
+
     OIC_LOG(INFO, TAG, "Exit HandleCAResponses");
 }
 
@@ -1384,21 +1447,39 @@ void HandleCAResponses(const CAEndpoint_t* endPoint, const CAResponseInfo_t* res
  * This function handles error response from CA
  * code shall be added to handle the errors
  */
-void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errrorInfo)
+void HandleCAErrorResponse(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
 {
     OIC_LOG(INFO, TAG, "Enter HandleCAErrorResponse");
 
-    if(NULL == endPoint)
+    if (NULL == endPoint)
     {
         OIC_LOG(ERROR, TAG, "endPoint is NULL");
         return;
     }
 
-    if(NULL == errrorInfo)
+    if (NULL == errorInfo)
     {
-        OIC_LOG(ERROR, TAG, "errrorInfo is NULL");
+        OIC_LOG(ERROR, TAG, "errorInfo is NULL");
         return;
     }
+
+    ClientCB *cbNode = GetClientCB(errorInfo->info.token,
+                                   errorInfo->info.tokenLength, NULL, NULL);
+    if (cbNode)
+    {
+        OCClientResponse response = { .devAddr = { .adapter = OC_DEFAULT_ADAPTER } };
+        CopyEndpointToDevAddr(endPoint, &response.devAddr);
+        FixUpClientResponse(&response);
+        response.resourceUri = errorInfo->info.resourceUri;
+        memcpy(response.identity.id, errorInfo->info.identity.id,
+               sizeof (response.identity.id));
+        response.identity.id_length = errorInfo->info.identity.id_length;
+        response.result = CAResultToOCStackResult(errorInfo->result);
+
+        cbNode->callBack(cbNode->context, cbNode->handle, &response);
+        FindAndDeleteClientCB(cbNode);
+    }
+
     OIC_LOG(INFO, TAG, "Exit HandleCAErrorResponse");
 }
 
@@ -1412,6 +1493,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
     };
@@ -1436,72 +1518,147 @@ 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)
+    {
+        OIC_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)
+            {
+                OIC_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)
+        {
+            OIC_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);
+        }
     }
+    OIC_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);
+void OCHandleRequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* requestInfo)
+{
+    OIC_LOG(DEBUG, TAG, "Enter OCHandleRequests");
+
+#ifdef TCP_ADAPTER
+    if (requestInfo->info.resourceUri &&
+            strcmp(requestInfo->info.resourceUri, KEEPALIVE_RESOURCE_URI) == 0)
+    {
+        HandleKeepAliveRequest(endPoint, requestInfo);
+        return;
+    }
 #endif
 
     OCStackResult requestResult = OC_STACK_ERROR;
@@ -1561,6 +1718,11 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     {
         serverRequest.reqTotalSize = requestInfo->info.payloadSize;
         serverRequest.payload = (uint8_t *) OICMalloc(requestInfo->info.payloadSize);
+        if (!serverRequest.payload)
+        {
+            OIC_LOG(ERROR, TAG, "Allocation for payload failed.");
+            return;
+        }
         memcpy (serverRequest.payload, requestInfo->info.payload,
                 requestInfo->info.payloadSize);
     }
@@ -1673,10 +1835,13 @@ void HandleCARequests(const CAEndpoint_t* endPoint, const CARequestInfo_t* reque
     requestResult = HandleStackRequests (&serverRequest);
 
     // Send ACK to client as precursor to slow response
-    if(requestResult == OC_STACK_SLOW_RESOURCE)
+    if (requestResult == OC_STACK_SLOW_RESOURCE)
     {
-        SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
-                    CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
+        if (requestInfo->info.type == CA_MSG_CONFIRM)
+        {
+            SendDirectStackResponse(endPoint, requestInfo->info.messageId, CA_EMPTY,
+                                    CA_MSG_ACKNOWLEDGE,0, NULL, NULL, 0, NULL);
+        }
     }
     else if(requestResult != OC_STACK_OK)
     {
@@ -1694,72 +1859,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)
@@ -1916,6 +2085,10 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
     }
     VERIFY_SUCCESS(result, OC_STACK_OK);
 
+#ifdef TCP_ADAPTER
+    CARegisterKeepAliveHandler(HandleKeepAliveConnCB);
+#endif
+
 #ifdef WITH_PRESENCE
     PresenceTimeOutSize = sizeof (PresenceTimeOut) / sizeof (PresenceTimeOut[0]) - 1;
 #endif // WITH_PRESENCE
@@ -1935,13 +2108,22 @@ 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)
+    {
+        result = InitializeKeepAlive(myStackMode);
+    }
+#endif
 
 exit:
     if(result != OC_STACK_OK)
@@ -1984,6 +2166,10 @@ OCStackResult OCStop()
     }
 #endif
 
+#ifdef TCP_ADAPTER
+    TerminateKeepAlive(myStackMode);
+#endif
+
     // Free memory dynamically allocated for resources
     deleteAllResources();
     DeleteDeviceInfo();
@@ -2044,31 +2230,6 @@ CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
     }
 }
 
-OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
-{
-    char *query;
-
-    query = strchr (inputUri, '?');
-
-    if (query != NULL)
-    {
-        if((query - inputUri) > MAX_URI_LENGTH)
-        {
-            return OC_STACK_INVALID_URI;
-        }
-
-        if((inputUri + uriLen - 1 - query) > MAX_QUERY_LENGTH)
-        {
-            return OC_STACK_INVALID_QUERY;
-        }
-    }
-    else if(uriLen > MAX_URI_LENGTH)
-    {
-        return OC_STACK_INVALID_URI;
-    }
-    return OC_STACK_OK;
-}
-
 /**
  *  A request uri consists of the following components in order:
  *                              example
@@ -2155,7 +2316,15 @@ static OCStackResult ParseRequestUri(const char *fullUri,
             {
                 colon = close + 1;
             }
-            adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
+
+            if (istcp)
+            {
+                adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
+            }
+            else
+            {
+                adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
+            }
             flags = (OCTransportFlags)(flags | OC_IP_USE_V6);
         }
         else
@@ -2167,14 +2336,15 @@ static OCStackResult ParseRequestUri(const char *fullUri,
                 end = (colon && colon < slash) ? colon : slash;
 
                 if (istcp)
-                {   // coap over tcp
+                {
+                    // coap over tcp
                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
                 }
                 else
                 {
                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
-                    flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
                 }
+                flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
             }
             else
             {   // MAC address
@@ -2335,13 +2505,6 @@ OCStackResult OCDoResource(OCDoHandle *handle,
     char *resourceUri = NULL;
     char *resourceType = NULL;
 
-    // This validation is broken, but doesn't cause harm
-    size_t uriLen = strlen(requestUri );
-    if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
-    {
-        goto exit;
-    }
-
     /*
      * Support original behavior with address on resourceUri argument.
      */
@@ -2480,12 +2643,6 @@ OCStackResult OCDoResource(OCDoHandle *handle,
         requestInfo.info.payloadFormat = CA_FORMAT_UNDEFINED;
     }
 
-    if (result != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "CACreateEndpoint error");
-        goto exit;
-    }
-
     // prepare for response
 #ifdef WITH_PRESENCE
     if (method == OC_REST_PRESENCE)
@@ -2592,9 +2749,11 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
         case OC_REST_OBSERVE:
         case OC_REST_OBSERVE_ALL:
 
-            OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s",
-                                        clientCB->requestUri);
-            if (qos != OC_HIGH_QOS)
+            OIC_LOG_V(INFO, TAG, "Canceling observation for resource %s", clientCB->requestUri);
+
+            CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
+
+            if ((endpoint.adapter & CA_ADAPTER_IP) && qos != OC_HIGH_QOS)
             {
                 FindAndDeleteClientCB(clientCB);
                 break;
@@ -2614,7 +2773,6 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
             requestInfo.info.numOptions = numOptions + 1;
             requestInfo.info.resourceUri = OICStrdup (clientCB->requestUri);
 
-            CopyDevAddrToEndpoint(clientCB->devAddr, &endpoint);
 
             ret = OCSendRequest(&endpoint, &requestInfo);
 
@@ -2786,6 +2944,10 @@ OCStackResult OCProcess()
 #ifdef ROUTING_GATEWAY
     RMProcess();
 #endif
+
+#ifdef TCP_ADAPTER
+    ProcessKeepAlive();
+#endif
     return OC_STACK_OK;
 }
 
@@ -2906,6 +3068,23 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
         return OC_STACK_INVALID_PARAM;
     }
 
+    if (deviceInfo.types)
+    {
+        OCStringLL *type =  deviceInfo.types;
+        OCResource *resource = findResource((OCResource *) deviceResource);
+        if (!resource)
+        {
+            return OC_STACK_INVALID_PARAM;
+        }
+        deleteResourceType(resource->rsrcType);
+        resource->rsrcType = NULL;
+
+        while (type)
+        {
+            OCBindResourceTypeToResource(deviceResource, type->value);
+            type = type->next;
+        }
+    }
     return SaveDeviceInfo(deviceInfo);
 }
 
@@ -3021,6 +3200,9 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
         pointer->entityHandlerCallbackParam = NULL;
     }
 
+    // Initialize a pointer indicating child resources in case of collection
+    pointer->rsrcChildResourcesHead = NULL;
+
     *handle = pointer;
     result = OC_STACK_OK;
 
@@ -3040,12 +3222,12 @@ exit:
     return result;
 }
 
-
 OCStackResult OCBindResource(
         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
 {
     OCResource *resource = NULL;
-    uint8_t i = 0;
+    OCChildResource *tempChildResource = NULL;
+    OCChildResource *newChildResource = NULL;
 
     OIC_LOG(INFO, TAG, "Entering OCBindResource");
 
@@ -3069,35 +3251,54 @@ OCStackResult OCBindResource(
 
     // Look for an open slot to add add the child resource.
     // If found, add it and return success
-    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+
+    tempChildResource = resource->rsrcChildResourcesHead;
+
+    while(resource->rsrcChildResourcesHead && tempChildResource->next)
     {
-        if (!resource->rsrcResources[i])
-        {
-            resource->rsrcResources[i] = (OCResource *) resourceHandle;
-            OIC_LOG(INFO, TAG, "resource bound");
+        // TODO: what if one of child resource was deregistered without unbinding?
+        tempChildResource = tempChildResource->next;
+    }
 
-#ifdef WITH_PRESENCE
-            if (presenceResource.handle)
-            {
-                ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
-                SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
-                        OC_PRESENCE_TRIGGER_CHANGE);
-            }
-#endif
-            return OC_STACK_OK;
+    // Do memory allocation for child resource
+    newChildResource = (OCChildResource *) OICCalloc(1, sizeof(OCChildResource));
+    if(!newChildResource)
+    {
+        OIC_LOG(ERROR, TAG, "Adding new child resource is failed due to memory allocation failure");
+        return OC_STACK_ERROR;
+    }
 
-        }
+    newChildResource->rsrcResource = (OCResource *) resourceHandle;
+    newChildResource->next = NULL;
+
+    if(!resource->rsrcChildResourcesHead)
+    {
+        resource->rsrcChildResourcesHead = newChildResource;
+    }
+    else {
+        tempChildResource->next = newChildResource;
     }
 
-    // Unable to add resourceHandle, so return error
-    return OC_STACK_ERROR;
+    OIC_LOG(INFO, TAG, "resource bound");
+
+#ifdef WITH_PRESENCE
+    if (presenceResource.handle)
+    {
+        ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+        SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType,
+                OC_PRESENCE_TRIGGER_CHANGE);
+    }
+#endif
+
+    return OC_STACK_OK;
 }
 
 OCStackResult OCUnBindResource(
         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
 {
     OCResource *resource = NULL;
-    uint8_t i = 0;
+    OCChildResource *tempChildResource = NULL;
+    OCChildResource *tempLastChildResource = NULL;
 
     OIC_LOG(INFO, TAG, "Entering OCUnBindResource");
 
@@ -3121,11 +3322,37 @@ OCStackResult OCUnBindResource(
 
     // Look for an open slot to add add the child resource.
     // If found, add it and return success
-    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    if(!resource->rsrcChildResourcesHead)
     {
-        if (resourceHandle == resource->rsrcResources[i])
+        OIC_LOG(INFO, TAG, "resource not found in collection");
+
+        // Unable to add resourceHandle, so return error
+        return OC_STACK_ERROR;
+
+    }
+
+    tempChildResource = resource->rsrcChildResourcesHead;
+
+    while (tempChildResource)
+    {
+        if(tempChildResource->rsrcResource == resourceHandle)
         {
-            resource->rsrcResources[i] = (OCResource *) NULL;
+            // if resource going to be unbinded is the head one.
+            if( tempChildResource == resource->rsrcChildResourcesHead )
+            {
+                OCChildResource *temp = resource->rsrcChildResourcesHead->next;
+                OICFree(resource->rsrcChildResourcesHead);
+                resource->rsrcChildResourcesHead = temp;
+                temp = NULL;
+            }
+            else
+            {
+                OCChildResource *temp = tempChildResource->next;
+                OICFree(tempChildResource);
+                tempLastChildResource->next = temp;
+                temp = NULL;
+            }
+
             OIC_LOG(INFO, TAG, "resource unbound");
 
             // Send notification when resource is unbounded successfully.
@@ -3137,39 +3364,66 @@ OCStackResult OCUnBindResource(
                         OC_PRESENCE_TRIGGER_CHANGE);
             }
 #endif
+            tempChildResource = NULL;
+            tempLastChildResource = NULL;
+
             return OC_STACK_OK;
+
         }
+
+        tempLastChildResource = tempChildResource;
+        tempChildResource = tempChildResource->next;
     }
 
     OIC_LOG(INFO, TAG, "resource not found in collection");
 
+    tempChildResource = NULL;
+    tempLastChildResource = NULL;
+
     // Unable to add resourceHandle, so return error
     return OC_STACK_ERROR;
 }
 
-// Precondition is that the parameter has been checked to not equal NULL.
 static bool ValidateResourceTypeInterface(const char *resourceItemName)
 {
-    if (resourceItemName[0] < 'a' || resourceItemName[0] > 'z')
+    if (!resourceItemName)
     {
         return false;
     }
-
-    size_t index = 1;
-    while (resourceItemName[index] != '\0')
+    // Per RFC 6690 only registered values must follow the first rule below.
+    // At this point in time the only values registered begin with "core", and
+    // all other values are specified as opaque strings where multiple values
+    // are separated by a space.
+    if (strncmp(resourceItemName, CORESPEC, sizeof(CORESPEC) - 1) == 0)
     {
-        if (resourceItemName[index] != '.' &&
-                resourceItemName[index] != '-' &&
-                (resourceItemName[index] < 'a' || resourceItemName[index] > 'z') &&
-                (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
+        for(size_t index = sizeof(CORESPEC) - 1;  resourceItemName[index]; ++index)
         {
-            return false;
+            if (resourceItemName[index] != '.'
+                && resourceItemName[index] != '-'
+                && (resourceItemName[index] < 'a' || resourceItemName[index] > 'z')
+                && (resourceItemName[index] < '0' || resourceItemName[index] > '9'))
+            {
+                return false;
+            }
+        }
+    }
+    else
+    {
+        for (size_t index = 0; resourceItemName[index]; ++index)
+        {
+            if (resourceItemName[index] == ' '
+                || resourceItemName[index] == '\t'
+                || resourceItemName[index] == '\r'
+                || resourceItemName[index] == '\n')
+            {
+                return false;
+            }
         }
-        ++index;
     }
 
     return true;
 }
+
 OCStackResult BindResourceTypeToResource(OCResource* resource,
                                             const char *resourceTypeName)
 {
@@ -3199,11 +3453,12 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
         goto exit;
     }
     pointer->resourcetypename = str;
+    pointer->next = NULL;
 
     insertResourceType(resource, pointer);
     result = OC_STACK_OK;
 
-    exit:
+exit:
     if (result != OC_STACK_OK)
     {
         OICFree(pointer);
@@ -3462,19 +3717,30 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa
         uint8_t index)
 {
     OCResource *resource = NULL;
+    OCChildResource *tempChildResource = NULL;
+    uint8_t num = 0;
 
-    if (index >= MAX_CONTAINED_RESOURCES)
+    resource = findResource((OCResource *) collectionHandle);
+    if (!resource)
     {
         return NULL;
     }
 
-    resource = findResource((OCResource *) collectionHandle);
-    if (!resource)
+    tempChildResource = resource->rsrcChildResourcesHead;
+
+    while(tempChildResource)
     {
-        return NULL;
+        if( num == index )
+        {
+            return tempChildResource->rsrcResource;
+        }
+        num++;
+        tempChildResource = tempChildResource->next;
     }
 
-    return resource->rsrcResources[index];
+    // In this case, the number of resource handles in the collection exceeds the index
+    tempChildResource = NULL;
+    return NULL;
 }
 
 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
@@ -3670,6 +3936,44 @@ OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse)
     return result;
 }
 
+//#ifdef DIRECT_PAIRING
+const OCDPDev_t* OCDiscoverDirectPairingDevices(unsigned short waittime)
+{
+    OIC_LOG(INFO, TAG, "Start OCDiscoverDirectPairingDevices");
+    if(OC_STACK_OK != DPDeviceDiscovery(waittime))
+    {
+        OIC_LOG(ERROR, TAG, "Fail to discover Direct-Pairing device");
+        return NULL;
+    }
+
+    return (const OCDPDev_t*)DPGetDiscoveredDevices();
+}
+
+const OCDPDev_t* OCGetDirectPairedDevices()
+{
+    return (const OCDPDev_t*)DPGetPairedDevices();
+}
+
+OCStackResult OCDoDirectPairing(void *ctx, OCDPDev_t* peer, OCPrm_t pmSel, char *pinNumber,
+                                                     OCDirectPairingCB resultCallback)
+{
+    OIC_LOG(INFO, TAG, "Start OCDoDirectPairing");
+    if(NULL ==  peer || NULL == pinNumber)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid parameters");
+        return OC_STACK_INVALID_PARAM;
+    }
+    if (NULL == resultCallback)
+    {
+        OIC_LOG(ERROR, TAG, "Invalid callback");
+        return OC_STACK_INVALID_CALLBACK;
+    }
+
+    return DPDirectPairing(ctx, (OCDirectPairingDev_t*)peer, (OicSecPrm_t)pmSel,
+                                           pinNumber, (OCDirectPairingResultCB)resultCallback);
+}
+//#endif // DIRECT_PAIRING
+
 //-----------------------------------------------------------------------------
 // Private internal function definitions
 //-----------------------------------------------------------------------------
@@ -3972,7 +4276,11 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType)
             previous = pointer;
             pointer = pointer->next;
         }
-        previous->next = resourceType;
+
+        if (previous)
+        {
+            previous->next = resourceType;
+        }
     }
     resourceType->next = NULL;
 
@@ -4042,8 +4350,27 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
 
     if (!*firstInterface)
     {
-        *firstInterface = newInterface;
+        // If first interface is not oic.if.baseline, by default add it as first interface type.
+        if (0 == strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT))
+        {
+            *firstInterface = newInterface;
+        }
+        else
+        {
+            OCStackResult result = BindResourceInterfaceToResource(resource, OC_RSRVD_INTERFACE_DEFAULT);
+            if (result != OC_STACK_OK)
+            {
+                OICFree(newInterface->name);
+                OICFree(newInterface);
+                return;
+            }
+            if (*firstInterface)
+            {
+                (*firstInterface)->next = newInterface;
+            }
+        }
     }
+    // If once add oic.if.baseline, later too below code take care of freeing memory.
     else if (strcmp(newInterface->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
     {
         if (strcmp((*firstInterface)->name, OC_RSRVD_INTERFACE_DEFAULT) == 0)
@@ -4052,6 +4379,7 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
             OICFree(newInterface);
             return;
         }
+        // This code will not hit anymore, keeping
         else
         {
             newInterface->next = *firstInterface;
@@ -4072,7 +4400,11 @@ void insertResourceInterface(OCResource *resource, OCResourceInterface *newInter
             previous = pointer;
             pointer = pointer->next;
         }
-        previous->next = newInterface;
+
+        if (previous)
+        {
+            previous->next = newInterface;
+        }
     }
 }
 
@@ -4168,7 +4500,7 @@ OCStackResult getQueryFromUri(const char * uri, char** query, char ** uriWithout
         return OC_STACK_NO_MEMORY;
 }
 
-const OicUuid_t* OCGetServerInstanceID(void)
+static const OicUuid_t* OCGetServerInstanceID(void)
 {
     static bool generated = false;
     static OicUuid_t sid;
@@ -4177,7 +4509,7 @@ const OicUuid_t* OCGetServerInstanceID(void)
         return &sid;
     }
 
-    if (GetDoxmDeviceID(&sid) != OC_STACK_OK)
+    if (OC_STACK_OK != GetDoxmDeviceID(&sid))
     {
         OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
         return NULL;
@@ -4196,8 +4528,7 @@ const char* OCGetServerInstanceIDString(void)
         return sidStr;
     }
 
-    const OicUuid_t* sid = OCGetServerInstanceID();
-
+    const OicUuid_t *sid = OCGetServerInstanceID();
     if(OCConvertUuidToString(sid->id, sidStr) != RAND_UUID_OK)
     {
         OIC_LOG(FATAL, TAG, "Generate UUID String for Server Instance failed!");
@@ -4216,8 +4547,8 @@ CAResult_t OCSelectNetwork()
     CATransportAdapter_t connTypes[] = {
             CA_ADAPTER_IP,
             CA_ADAPTER_RFCOMM_BTEDR,
-            CA_ADAPTER_GATT_BTLE
-
+            CA_ADAPTER_GATT_BTLE,
+            CA_ADAPTER_NFC
 #ifdef RA_ADAPTER
             ,CA_ADAPTER_REMOTE_ACCESS
 #endif