Merge remote-tracking branch 'origin/routing-manager'
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / camessagehandler.c
index 9552827..982f1a8 100644 (file)
@@ -1,4 +1,4 @@
-/******************************************************************
+/* *****************************************************************
  *
  * Copyright 2014 Samsung Electronics All Rights Reserved.
  *
 #include "cainterface.h"
 #include "camessagehandler.h"
 #include "caremotehandler.h"
-#include "cainterfacecontroller.h"
-#include "uqueue.h"
+#include "caprotocolmessage.h"
 #include "logger.h"
 #include "config.h" /* for coap protocol */
-#include "coap.h"
-#include "uthreadpool.h" /* for thread pool */
-#include "umutex.h"
 #include "oic_malloc.h"
+#include "canetworkconfigurator.h"
+#include "caadapterutils.h"
+#include "cainterfacecontroller.h"
+#include "caretransmission.h"
 
-#define TAG PCF("CA")
+#ifdef WITH_BWT
+#include "cablockwisetransfer.h"
+#endif
 
-#define MEMORY_ALLOCK_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(DEBUG, TAG, "memory error"); goto memory_error_exit;} }
-#define MAX_ACTION_NUM   300
+#ifndef  SINGLE_THREAD
+#include "uqueue.h"
+#include "cathreadpool.h" /* for thread pool */
+#include "caqueueingthread.h"
 
-#define MAX_THREAD_POOL_SIZE    10
+#define SINGLE_HANDLE
+#define MAX_THREAD_POOL_SIZE    20
 
-#ifndef TRUE
-#define TRUE    1
-#endif
+// thread pool handle
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+
+// message handler main thread
+static CAQueueingThread_t g_sendThread;
+static CAQueueingThread_t g_receiveThread;
+
+#else
+#define CA_MAX_RT_ARRAY_SIZE    3
+#endif  /* SINGLE_THREAD */
+
+#define TAG "CA_MSG_HNDLR"
+
+static CARetransmission_t g_retransmissionContext;
+
+// handler field
+static CARequestCallback g_requestHandler = NULL;
+static CAResponseCallback g_responseHandler = NULL;
+static CAErrorCallback g_errorHandler = NULL;
+
+static void CAErrorHandler(const CAEndpoint_t *endpoint,
+                           const void *data, uint32_t dataLen,
+                           CAResult_t result);
+
+static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
+                                       const CARemoteId_t *identity,
+                                       const void *data, CADataType_t dataType);
+
+static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
+                            CAResult_t result);
 
-#ifndef FALSE
-#define FALSE   0
+#ifdef SINGLE_THREAD
+static void CAProcessReceivedData(CAData_t *data);
 #endif
+static void CADestroyData(void *data, uint32_t size);
+static void CALogPayloadInfo(CAInfo_t *info);
+static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
+                                CAToken_t token, uint8_t tokenLength);
 
-typedef struct
+#ifdef WITH_BWT
+void CAAddDataToSendThread(CAData_t *data)
 {
-    int32_t actionId;
-    CARemoteEndpoint_t* remoteEndpoint;
-    CARequestInfo_t* requestInfo;
-    CAResponseInfo_t* responseInfo;
-} CAData_t;
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
 
-typedef void (*CAThreadTask)(CAData_t* data);
+    // add thread
+    CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
 
-typedef struct
-{
-    u_mutex threadMutex;
-    u_cond threadCond;
-    CAThreadTask threadTask;
-    int32_t isStop;
-    u_queue_t* dataQueue;
-} CAThread_t;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
 
-// thread pool handle
-static u_thread_pool_t gThreadPoolHandle = NULL;
+void CAAddDataToReceiveThread(CAData_t *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN - CAAddDataToReceiveThread");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
 
-// message handler main thread
-static CAThread_t gSendThread;
+    // add thread
+    CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
 
-// message handler callback
-static int32_t gCurrentActionId = 0;
-static CAMessageHandlerCallback gHandlerCallback = NULL;
+    OIC_LOG(DEBUG, TAG, "OUT - CAAddDataToReceiveThread");
+}
+#endif
 
-// handler field
-static CARequestCallback gRequestHandler = NULL;
-static CAResponseCallback gResponseHandler = NULL;
+static bool CAIsSelectedNetworkAvailable()
+{
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+    if (!list || u_arraylist_length(list) == 0)
+    {
+        OIC_LOG(ERROR, TAG, "No selected network");
+        return false;
+    }
 
-static u_queue_t* gMessageQueue = NULL;
-static u_mutex gMessageQueueMutex = NULL;
+    return true;
+}
 
-static void CAAddReceiveData(CAData_t* data)
+static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
+                                       const CARemoteId_t *identity,
+                                       const void *data, CADataType_t dataType)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAAddReceiveData");
+    OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
+    CAInfo_t *info = NULL;
+    CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    if (!cadata)
+    {
+        OIC_LOG(ERROR, TAG, "memory allocation failed");
+        return NULL;
+    }
+
+    CAEndpoint_t* ep = CACloneEndpoint(endpoint);
+    if (!ep)
+    {
+        OIC_LOG(ERROR, TAG, "endpoint clone failed");
+        OICFree(cadata);
+        return NULL;
+    }
 
-    // create thread data
-    u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t));
+    OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
+    CAResult_t result;
 
-    if (message == NULL)
+    if(CA_RESPONSE_DATA == dataType)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory error!!");
-        return;
+        CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
+        if (!resInfo)
+        {
+            OIC_LOG(ERROR, TAG, "memory allocation failed");
+            OICFree(cadata);
+            CAFreeEndpoint(ep);
+            return NULL;
+        }
+
+        result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
+            CAFreeEndpoint(ep);
+            CADestroyResponseInfoInternal(resInfo);
+            OICFree(cadata);
+            return NULL;
+        }
+        cadata->responseInfo = resInfo;
+        info = &resInfo->info;
+        if (identity)
+        {
+            info->identity = *identity;
+        }
+        OIC_LOG(DEBUG, TAG, "Response Info :");
+        CALogPayloadInfo(info);
     }
-    memset(message, 0, sizeof(u_queue_message_t));
+    else if (CA_REQUEST_DATA == dataType)
+    {
+        CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
+        if (!reqInfo)
+        {
+            OIC_LOG(ERROR, TAG, "memory allocation failed");
+            OICFree(cadata);
+            CAFreeEndpoint(ep);
+            return NULL;
+        }
+
+        result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
+            CAFreeEndpoint(ep);
+            CADestroyRequestInfoInternal(reqInfo);
+            OICFree(cadata);
+            return NULL;
+        }
 
-    message->msg = data;
-    message->size = sizeof(CAData_t);
+        if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
+                                reqInfo->info.token, reqInfo->info.tokenLength))
+        {
+            OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
+            CAFreeEndpoint(ep);
+            CADestroyRequestInfoInternal(reqInfo);
+            OICFree(cadata);
+            return NULL;
+        }
+
+        cadata->requestInfo = reqInfo;
+        info = &reqInfo->info;
+        if (identity)
+        {
+            info->identity = *identity;
+        }
+        OIC_LOG(DEBUG, TAG, "Request Info :");
+        CALogPayloadInfo(info);
+   }
+    else if (CA_ERROR_DATA == dataType)
+    {
+        CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
+        if (!errorInfo)
+        {
+            OIC_LOG(ERROR, TAG, "Memory allocation failed!");
+            OICFree(cadata);
+            CAFreeEndpoint(ep);
+            return NULL;
+        }
+
+        CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
+        if (CA_STATUS_OK != result)
+        {
+            OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
+            CAFreeEndpoint(ep);
+            OICFree(errorInfo);
+            OICFree(cadata);
+            return NULL;
+        }
+
+        cadata->errorInfo = errorInfo;
+        info = &errorInfo->info;
+        if (identity)
+        {
+            info->identity = *identity;
+        }
+        OIC_LOG(DEBUG, TAG, "error Info :");
+        CALogPayloadInfo(info);
+    }
 
-    // mutex lock
-    u_mutex_lock(gMessageQueueMutex);
+    cadata->remoteEndpoint = ep;
+    cadata->dataType = dataType;
 
-    // add thread data into list
-    u_queue_add_element(gMessageQueue, message);
+    return cadata;
 
-    // mutex unlock
-    u_mutex_unlock(gMessageQueueMutex);
+    OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
 }
 
-static void CAAddSendData(CAData_t* data)
+static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAAddSendData!!");
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
+    VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
 
-    // create thread data
-    u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t));
+    CAEndpoint_t* ep = CACloneEndpoint(endpoint);
+    if (!ep)
+    {
+        OIC_LOG(ERROR, TAG, "clone failed");
+        return;
+    }
+
+    CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
 
-    if (message == NULL)
+    if (!resInfo)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory error!!");
+        OIC_LOG(ERROR, TAG, "calloc failed");
+        CAFreeEndpoint(ep);
         return;
     }
-    memset(message, 0, sizeof(u_queue_message_t));
 
-    message->msg = data;
-    message->size = sizeof(CAData_t);
+    resInfo->result = CA_RETRANSMIT_TIMEOUT;
+    resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
+    resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
 
-    // mutex lock
-    u_mutex_lock(gSendThread.threadMutex);
+    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
+                                       endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
+        CADestroyResponseInfoInternal(resInfo);
+        CAFreeEndpoint(ep);
+        return;
+    }
+
+    CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    if (NULL == cadata)
+    {
+        OIC_LOG(ERROR, TAG, "memory allocation failed !");
+        CAFreeEndpoint(ep);
+        CADestroyResponseInfoInternal(resInfo);
+        return;
+    }
 
-    // add thread data into list
-    u_queue_add_element(gSendThread.dataQueue, message);
+    cadata->type = SEND_TYPE_UNICAST;
+    cadata->remoteEndpoint = ep;
+    cadata->requestInfo = NULL;
+    cadata->responseInfo = resInfo;
 
-    // notity the thread
-    u_cond_signal(gSendThread.threadCond);
+#ifdef SINGLE_THREAD
+    CAProcessReceivedData(cadata);
+#else
+    CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+#endif
 
-    // mutex unlock
-    u_mutex_unlock(gSendThread.threadMutex);
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-static void CAStopSendThread()
+static void CADestroyData(void *data, uint32_t size)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAStopSendThread request!!");
+    OIC_LOG(DEBUG, TAG, "CADestroyData IN");
+    if ((size_t)size < sizeof(CAData_t))
+    {
+        OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
+    }
+    CAData_t *cadata = (CAData_t *) data;
 
-    // mutex lock
-    u_mutex_lock(gSendThread.threadMutex);
+    if (NULL == cadata)
+    {
+        OIC_LOG(ERROR, TAG, "cadata is NULL");
+        return;
+    }
 
-    // set stop flag
-    gSendThread.isStop = TRUE;
+    if (NULL != cadata->remoteEndpoint)
+    {
+        CAFreeEndpoint(cadata->remoteEndpoint);
+    }
+
+    if (NULL != cadata->requestInfo)
+    {
+        CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
+    }
+
+    if (NULL != cadata->responseInfo)
+    {
+        CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
+    }
 
-    // notity the thread
-    u_cond_signal(gSendThread.threadCond);
+    if (NULL != cadata->errorInfo)
+    {
+        CADestroyErrorInfoInternal(cadata->errorInfo);
+    }
 
-    // mutex unlock
-    u_mutex_unlock(gSendThread.threadMutex);
+    OICFree(cadata);
+    OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
 }
 
-static void CASendThreadProcess(CAData_t* data)
+#ifdef SINGLE_THREAD
+static void CAProcessReceivedData(CAData_t *data)
 {
-    if (data == NULL)
+    OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
+    if (!data)
     {
-        OIC_LOG(DEBUG, TAG, "thread data error!!");
+        OIC_LOG(ERROR, TAG, "thread data error!!");
         return;
     }
 
-    if (NULL == data->remoteEndpoint)
+    // parse the data and call the callbacks.
+    // #1 parse the data
+    // #2 get endpoint
+    CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
+    if (!rep)
     {
-        OIC_LOG(DEBUG, TAG, "remoteEndpoint is null");
+        OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
         return;
     }
 
-    OIC_LOG_V(DEBUG, TAG, "thread action id : %d", data->actionId);
+    if (data->requestInfo && g_requestHandler)
+    {
+        g_requestHandler(rep, data->requestInfo);
+    }
+    else if (data->responseInfo && g_responseHandler)
+    {
+        g_responseHandler(rep, data->responseInfo);
+    }
+    else if (data->errorInfo && g_errorHandler)
+    {
+        g_errorHandler(rep, data->errorInfo);
+    }
+
+#ifdef SINGLE_THREAD
+    CADestroyData(data, sizeof(CAData_t));
+#endif
 
-    CADetachErrorCode code = FAIL;
-    int32_t res = 0;
+    OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
+}
+#endif
 
-    if (data->requestInfo != NULL)
-    {
-        OIC_LOG(DEBUG, TAG, "requestInfo is available");
+#ifndef SINGLE_THREAD
 
-        coap_pdu_t* pdu = NULL;
-        pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, data->requestInfo->method,
-                data->requestInfo->info);
+static void CAReceiveThreadProcess(void *threadData)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+#ifndef SINGLE_HANDLE
+    CAData_t *data = (CAData_t *) threadData;
+    CAProcessReceivedData(data);
+#else
+    (void)threadData;
+#endif
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+#endif
 
-        // interface controller function call.
-        if (NULL != pdu)
-        {
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
+static CAResult_t CAProcessSendData(const CAData_t *data)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(data, TAG, "data");
+    VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
+    CAResult_t res = CA_STATUS_FAILED;
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %s", pdu->hdr);
+    CASendDataType_t type = data->type;
 
-            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
-        }
-    }
-    else if (data->responseInfo != NULL)
+    coap_pdu_t *pdu = NULL;
+    CAInfo_t *info = NULL;
+
+    if (SEND_TYPE_UNICAST == type)
     {
-        OIC_LOG_V(DEBUG, TAG, "responseInfo is available..");
+        OIC_LOG(DEBUG,TAG,"Unicast message");
+#ifdef ROUTING_GATEWAY
+        /*
+         * When forwarding a packet, do not attempt retransmission as its the responsibility of
+         * packet originator node
+         */
+        bool skipRetransmission = false;
+#endif
 
-        coap_pdu_t* pdu = NULL;
+        if (NULL != data->requestInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "requestInfo is available..");
 
-        pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, data->responseInfo->result,
-                data->responseInfo->info);
+            info = &data->requestInfo->info;
+#ifdef ROUTING_GATEWAY
+            skipRetransmission = data->requestInfo->info.skipRetransmission;
+#endif
+            pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint);
+        }
+        else if (NULL != data->responseInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "responseInfo is available..");
+
+            info = &data->responseInfo->info;
+#ifdef ROUTING_GATEWAY
+            skipRetransmission = data->responseInfo->info.skipRetransmission;
+#endif
+            pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG, "request info, response info is empty");
+            return CA_STATUS_INVALID_PARAM;
+        }
 
         // interface controller function call.
         if (NULL != pdu)
         {
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
-
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
-
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %x", pdu->hdr);
+#ifdef WITH_BWT
+            if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
+#ifdef TCP_ADAPTER
+                    && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
+#endif
+                    )
+            {
+                // Blockwise transfer
+                if (NULL != info)
+                {
+                    CAResult_t res = CAAddBlockOption(&pdu, *info,
+                                                      data->remoteEndpoint);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG(INFO, TAG, "to write block option has failed");
+                        CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+                        coap_delete_pdu(pdu);
+                        return res;
+                    }
+                }
+            }
+#endif
+            CALogPDUInfo(pdu, data->remoteEndpoint);
 
             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+            if (CA_STATUS_OK != res)
+            {
+                OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+                CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+                coap_delete_pdu(pdu);
+                return res;
+            }
+
+#ifdef TCP_ADAPTER
+            if (CA_ADAPTER_TCP == data->remoteEndpoint->adapter)
+            {
+                OIC_LOG(INFO, TAG, "retransmission will be not worked");
+            }
+            else
+#endif
+#ifdef ROUTING_GATEWAY
+            if(!skipRetransmission)
+#endif
+            {
+                // for retransmission
+                res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
+                                               pdu->length);
+                if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
+                {
+                    //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
+                    OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
+                    coap_delete_pdu(pdu);
+                    return res;
+                }
+            }
+
+            coap_delete_pdu(pdu);
+        }
+        else
+        {
+            OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
+            CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
+            return CA_SEND_FAILED;
         }
     }
-    else
+    else if (SEND_TYPE_MULTICAST == type)
     {
-        OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
-
-        coap_pdu_t* pdu = NULL;
-        CAInfo_t info;
-        memset(&info, 0, sizeof(CAInfo_t));
-        pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, CA_GET, info);
-
-        if (NULL != pdu)
+        OIC_LOG(DEBUG,TAG,"Multicast message");
+        if (NULL != data->requestInfo)
+        {
+            OIC_LOG(DEBUG, TAG, "requestInfo is available..");
+
+            info = &data->requestInfo->info;
+            pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint);
+            if (NULL != pdu)
+            {
+#ifdef WITH_BWT
+                if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
+#ifdef TCP_ADAPTER
+                        && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
+#endif
+                        )
+                {
+                    // Blockwise transfer
+                    CAResult_t res = CAAddBlockOption(&pdu, data->requestInfo->info,
+                                                      data->remoteEndpoint);
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
+                        CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+                        coap_delete_pdu(pdu);
+                        return res;
+                    }
+                }
+#endif
+            }
+            else
+            {
+                OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
+                CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
+                return CA_SEND_FAILED;
+            }
+        }
+        else if (NULL != data->responseInfo)
         {
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
+            OIC_LOG(DEBUG, TAG, "responseInfo is available..");
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
+            info = &data->responseInfo->info;
+            pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint);
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
+            if (NULL != pdu)
+            {
+#ifdef WITH_BWT
+                if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
+#ifdef TCP_ADAPTER
+                        && CA_ADAPTER_TCP != data->remoteEndpoint->adapter
+#endif
+                        )
+                {
+                    // Blockwise transfer
+                    if (NULL != info)
+                    {
+                        CAResult_t res = CAAddBlockOption(&pdu, *info,
+                                data->remoteEndpoint);
+                        if (CA_STATUS_OK != res)
+                        {
+                            OIC_LOG(INFO, TAG, "to write block option has failed");
+                            CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+                            coap_delete_pdu(pdu);
+                            return res;
+                        }
+                    }
+                }
+#endif
+            }
+            else
+            {
+                OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
+                CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
+                return CA_SEND_FAILED;
+            }
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "request or response info is empty");
+            return CA_SEND_FAILED;
+        }
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", pdu->hdr->id);
+        CALogPDUInfo(pdu, data->remoteEndpoint);
 
-            OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %x", pdu->hdr);
+        OIC_LOG(DEBUG, TAG, "pdu to send :");
+        OIC_LOG_BUFFER(DEBUG, TAG,  pdu->hdr, pdu->length);
 
-            res = CASendMulticastData(pdu->hdr, pdu->length);
+        res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+            CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+            coap_delete_pdu(pdu);
+            return res;
         }
 
+        coap_delete_pdu(pdu);
     }
 
-    if (res)
-    {
-        code = SUCCESS;
-    }
-
-    if (gHandlerCallback != NULL)
-    {
-        gHandlerCallback(data->actionId, code);
-    }
+    return CA_STATUS_OK;
 }
 
-static void* CAThreadBaseRoutine(void* treadData)
+#ifndef SINGLE_THREAD
+static void CASendThreadProcess(void *threadData)
 {
-    OIC_LOG_V(DEBUG, TAG, "message handler main thread start..");
+    CAData_t *data = (CAData_t *) threadData;
+    CAProcessSendData(data);
+}
 
-    CAThread_t* thread = (CAThread_t*) treadData;
+#endif
 
-    if (thread == NULL)
+/*
+ * If a second message arrives with the same message ID, token and the other address
+ * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
+ */
+static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
+                                CAToken_t token, uint8_t tokenLength)
+{
+    if (!ep)
     {
-        OIC_LOG_V(DEBUG, TAG, "thread data passing error!!");
-
-        return NULL;
+        return true;
+    }
+    if (ep->adapter != CA_ADAPTER_IP)
+    {
+        return false;
+    }
+    if (!caglobals.ip.dualstack)
+    {
+        return false;
     }
 
-    while (!thread->isStop)
+    if (tokenLength > CA_MAX_TOKEN_LEN)
     {
-        // mutex lock
-        u_mutex_lock(thread->threadMutex);
+        /*
+         * If token length is more than CA_MAX_TOKEN_LEN,
+         * we compare the first CA_MAX_TOKEN_LEN bytes only.
+         */
+        tokenLength = CA_MAX_TOKEN_LEN;
+    }
 
-        // if queue is empty, thread will wait
-        if (u_queue_get_size(thread->dataQueue) <= 0)
-        {
-            OIC_LOG_V(DEBUG, TAG, "wait..");
-            // wait
-            u_cond_wait(thread->threadCond, thread->threadMutex);
+    bool ret = false;
+    CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
 
-            OIC_LOG_V(DEBUG, TAG, "wake up..");
+    for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
+    {
+        CAHistoryItem_t *item = &(history->items[i]);
+        if (id == item->messageId && tokenLength == item->tokenLength
+            && memcmp(item->token, token, tokenLength) == 0)
+        {
+            if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
+            {
+                OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
+                                            familyFlags & CA_IPV6 ? '6' : '4');
+                ret = true;
+                break;
+            }
         }
+    }
 
-        // mutex unlock
-        u_mutex_unlock(thread->threadMutex);
-
-        // check stop flag
-        if (thread->isStop)
-            continue;
-
-        // get data
-        u_queue_message_t* message = u_queue_get_element(thread->dataQueue);
-
-        CAData_t* data = (CAData_t*) message->msg;
-
-        // process data
-        thread->threadTask(data);
+    history->items[history->nextIndex].flags = familyFlags;
+    history->items[history->nextIndex].messageId = id;
+    if (token && tokenLength)
+    {
+        memcpy(history->items[history->nextIndex].token, token, tokenLength);
+        history->items[history->nextIndex].tokenLength = tokenLength;
     }
 
-    OIC_LOG_V(DEBUG, TAG, "message handler main thread end..");
+    if (++history->nextIndex >= HISTORYSIZE)
+    {
+        history->nextIndex = 0;
+    }
 
-    return NULL;
+    return ret;
 }
 
-static int32_t CAIncreaseActionId()
+static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
+                                     const void *data, uint32_t dataLen)
 {
-    ++gCurrentActionId;
-
-    gCurrentActionId = (gCurrentActionId > MAX_ACTION_NUM) ? 0 : gCurrentActionId;
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
 
-    return gCurrentActionId;
-}
+    OIC_LOG(DEBUG, TAG, "received pdu data :");
+    OIC_LOG_BUFFER(DEBUG, TAG,  data, dataLen);
 
-static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, TAG, "receivedPacketCallback in message handler!!");
+    uint32_t code = CA_NOT_FOUND;
+    CAData_t *cadata = NULL;
 
-    if (NULL == data)
+    coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
+                                                &(sep->endpoint));
+    if (NULL == pdu)
     {
-        OIC_LOG(DEBUG, TAG, "received data is null");
+        OIC_LOG(ERROR, TAG, "Parse PDU failed");
         return;
     }
 
-    coap_pdu_t* pdu;
-    uint32_t code = CA_NOT_FOUND;
-    pdu = CAParsePDU(data, &code);
-
-    if (code == CA_GET || code == CA_POST || code == CA_PUT || code == CA_DELETE)
+    OIC_LOG_V(DEBUG, TAG, "code = %d", code);
+    if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
     {
-        CARequestInfo_t ReqInfo;
-        memset(&ReqInfo, 0, sizeof(CARequestInfo_t));
-        CAGetRequestInfoFromPdu(pdu, &ReqInfo);
-
-        if (NULL != ReqInfo.info.options && NULL != endpoint)
+        cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
+        if (!cadata)
         {
-            OIC_LOG_V(DEBUG, TAG, "Request PDU - optionID: %d", ReqInfo.info.options->optionID);
-
-            OIC_LOG_V(DEBUG, TAG, "Request PDU - optionlist: %s", ReqInfo.info.options->optionData);
-
-            OIC_LOG_V(DEBUG, TAG, "Request PDU  - payload: %s", ReqInfo.info.payload);
-
-            OIC_LOG_V(DEBUG, TAG, "Request PDU  - code: %d", ReqInfo.method);
-
-            endpoint->resourceUri = (char*) OICMalloc(strlen(ReqInfo.info.options->optionData) + 1);
-            memcpy(endpoint->resourceUri, ReqInfo.info.options->optionData,
-                    strlen(ReqInfo.info.options->optionData));
-            OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
+            coap_delete_pdu(pdu);
+            return;
         }
-
-        // store the data at queue.
-        CAData_t* cadata = NULL;
-        cadata = (CAData_t*) OICMalloc(sizeof(CAData_t));
-        memset(cadata, 0, sizeof(CAData_t));
-        cadata->actionId = 1;
-        cadata->remoteEndpoint = endpoint;
-        cadata->requestInfo = &ReqInfo;
-        cadata->responseInfo = NULL;
-        CAAddReceiveData(cadata);
-
     }
     else
     {
-        CAResponseInfo_t ResInfo;
-        memset(&ResInfo, 0, sizeof(CARequestInfo_t));
-        CAGetResponseInfoFromPdu(pdu, &ResInfo);
+        cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
+        if (!cadata)
+        {
+            OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
+            coap_delete_pdu(pdu);
+            return;
+        }
 
-        if (NULL != ResInfo.info.options && NULL != endpoint)
+#ifdef TCP_ADAPTER
+        if (CA_ADAPTER_TCP == sep->endpoint.adapter)
         {
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - optionID: %d", ResInfo.info.options->optionID);
+            OIC_LOG(INFO, TAG, "retransmission is not supported");
+        }
+        else
+#endif
+        {
+            // for retransmission
+            void *retransmissionPdu = NULL;
+            CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
+                                         pdu->length, &retransmissionPdu);
+
+            // get token from saved data in retransmission list
+            if (retransmissionPdu && CA_EMPTY == code)
+            {
+                if (cadata->responseInfo)
+                {
+                    CAInfo_t *info = &cadata->responseInfo->info;
+                    CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
+                                                       info, &(sep->endpoint));
+                    if (CA_STATUS_OK != res)
+                    {
+                        OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
+                        OICFree(info->token);
+                        info->tokenLength = 0;
+                    }
+                }
+            }
+            OICFree(retransmissionPdu);
+        }
+    }
+
+    cadata->type = SEND_TYPE_UNICAST;
 
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - optionlist: %s", ResInfo.info.options->optionData);
+#ifdef SINGLE_THREAD
+    CAProcessReceivedData(cadata);
+#else
+#ifdef WITH_BWT
+    if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
+#ifdef TCP_ADAPTER
+            && CA_ADAPTER_TCP != sep->endpoint.adapter
+#endif
+            )
+    {
+        CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
+        if (CA_NOT_SUPPORTED == res)
+        {
+            OIC_LOG(ERROR, TAG, "this message does not have block option");
+            CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+        }
+        else
+        {
+            CADestroyData(cadata, sizeof(CAData_t));
+        }
+    }
+    else
+#endif
+    {
+        CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+    }
+#endif
 
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - payload: %s", ResInfo.info.payload);
+    coap_delete_pdu(pdu);
 
-            OIC_LOG_V(DEBUG, TAG, "Response PDU - code: %d", ResInfo.result);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
 
-            endpoint->resourceUri = (char*) OICMalloc(strlen(ResInfo.info.options->optionData) + 1);
-            memcpy(endpoint->resourceUri, ResInfo.info.options->optionData,
-                    strlen(ResInfo.info.options->optionData));
-            OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
-        }
+static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
+{
+    (void)info;
+    (void)status;
+    OIC_LOG(DEBUG, TAG, "IN");
 
-        // store the data at queue.
-        CAData_t* cadata = NULL;
-        cadata = (CAData_t*) OICMalloc(sizeof(CAData_t));
-        memset(cadata, 0, sizeof(CAData_t));
-        cadata->actionId = 1;
-        cadata->remoteEndpoint = endpoint;
-        cadata->requestInfo = NULL;
-        cadata->responseInfo = &ResInfo;
-        CAAddReceiveData(cadata);
-    }
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
 void CAHandleRequestResponseCallbacks()
 {
-    OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponseCallbacks");
-
+#ifdef SINGLE_THREAD
+    CAReadData();
+    CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
+#else
+#ifdef SINGLE_HANDLE
     // parse the data and call the callbacks.
     // #1 parse the data
     // #2 get endpoint
 
-    u_mutex_lock(gMessageQueueMutex);
+    ca_mutex_lock(g_receiveThread.threadMutex);
 
-    u_queue_message_t* item = u_queue_get_element(gMessageQueue);
+    u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
 
-    u_mutex_unlock(gMessageQueueMutex);
+    ca_mutex_unlock(g_receiveThread.threadMutex);
 
-    if (item == NULL)
+    if (NULL == item)
+    {
         return;
+    }
 
     // get values
-    voidmsg = item->msg;
+    void *msg = item->msg;
 
-    if (msg == NULL)
+    if (NULL == msg)
+    {
         return;
+    }
 
     // get endpoint
-    CAData_t* td = (CAData_t*) msg;
-
-    CARemoteEndpoint_t* rep = td->remoteEndpoint;
-
-    if (rep == NULL)
-        return;
+    CAData_t *td = (CAData_t *) msg;
 
-    if (td->requestInfo != NULL)
+    if (td->requestInfo && g_requestHandler)
     {
-        if (gRequestHandler)
-        {
-            gRequestHandler(rep, NULL);
-        }
+        OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
+        g_requestHandler(td->remoteEndpoint, td->requestInfo);
     }
-
-    if (td->responseInfo != NULL)
+    else if (td->responseInfo && g_responseHandler)
     {
-        if (gResponseHandler)
-        {
-            gResponseHandler(rep, NULL);
-        }
+        OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
+        g_responseHandler(td->remoteEndpoint, td->responseInfo);
+    }
+    else if (td->errorInfo && g_errorHandler)
+    {
+        OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
+        g_errorHandler(td->remoteEndpoint, td->errorInfo);
     }
 
-    u_queue_remove_element(gMessageQueue);
+    CADestroyData(msg, sizeof(CAData_t));
+    OICFree(item);
+
+#endif /* SINGLE_HANDLE */
+#endif
 }
 
-int32_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request)
+static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
+                                   CADataType_t dataType)
 {
-    OIC_LOG_V(DEBUG, TAG, "CADetachRequestMessage");
+    OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
 
-    if (object == NULL || request == NULL)
+    CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    if (!cadata)
     {
-        return -1;
+        OIC_LOG(ERROR, TAG, "memory allocation failed");
+        return NULL;
     }
 
-    int32_t id = 0;
+    if(CA_REQUEST_DATA == dataType)
+    {
+        // clone request info
+        CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
 
-    // create action id
-    id = CAIncreaseActionId();
+        if(!request)
+        {
+            OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
+            OICFree(cadata);
+            return NULL;
+        }
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
-    MEMORY_ALLOCK_CHECK(data);
+        cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
+        cadata->requestInfo =  request;
+    }
+    else if(CA_RESPONSE_DATA == dataType)
+    {
+        // clone response info
+        CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
 
-    // initialize
-    memset(data, 0, sizeof(CAData_t));
+        if(!response)
+        {
+            OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
+            OICFree(cadata);
+            return NULL;
+        }
+
+        cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
+        cadata->responseInfo = response;
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
+        OICFree(cadata);
+        return NULL;
+    }
 
-    // clone remote endpoint
-    CARemoteEndpoint_t* remoteEndpoint = CACloneRemoteEndpoint(object);
-    MEMORY_ALLOCK_CHECK(remoteEndpoint);
+    CAEndpoint_t* ep = CACloneEndpoint(endpoint);
+    if (!ep)
+    {
+        OIC_LOG(ERROR, TAG, "endpoint clone failed");
+        CADestroyData(cadata, sizeof(CAData_t));
+        return NULL;
+    }
 
-    // clone request info
-    CARequestInfo_t* requestInfo = CACloneRequestInfo(request);
-    MEMORY_ALLOCK_CHECK(requestInfo);
+    cadata->remoteEndpoint = ep;
+    cadata->dataType = dataType;
+    return cadata;
+}
 
-    // save data
-    data->actionId = id;
-    data->remoteEndpoint = remoteEndpoint;
-    data->requestInfo = requestInfo;
-    data->responseInfo = NULL;
+CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
 
-    // add thread
-    CAAddSendData(data);
+    VERIFY_NON_NULL(object, TAG, "object");
+    VERIFY_NON_NULL(request, TAG, "request");
 
-    return id;
+    if (false == CAIsSelectedNetworkAvailable())
+    {
+        return CA_STATUS_FAILED;
+    }
 
-    // memory error label.
-    memory_error_exit:
+#ifdef ARDUINO
+    // If max retransmission queue is reached, then don't handle new request
+    if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
+    {
+        OIC_LOG(ERROR, TAG, "max RT queue size reached!");
+        return CA_SEND_FAILED;
+    }
+#endif /* ARDUINO */
 
-    CADestroyRemoteEndpointInternal(remoteEndpoint);
+    CAData_t *data = CAPrepareSendData(object, request, CA_REQUEST_DATA);
+    if(!data)
+    {
+        OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
 
-    CADestroyRequestInfoInternal(requestInfo);
+#ifdef SINGLE_THREAD
+    CAResult_t result = CAProcessSendData(data);
+    if(CA_STATUS_OK != result)
+    {
+        OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
+        return result;
+    }
 
-    if (data != NULL)
+    CADestroyData(data, sizeof(CAData_t));
+#else
+#ifdef WITH_BWT
+    if (CA_ADAPTER_GATT_BTLE != object->adapter
+#ifdef TCP_ADAPTER
+            && CA_ADAPTER_TCP != object->adapter
+#endif
+            )
     {
-        OICFree(data);
+        // send block data
+        CAResult_t res = CASendBlockWiseData(data);
+        if(CA_NOT_SUPPORTED == res)
+        {
+            OIC_LOG(DEBUG, TAG, "normal msg will be sent");
+            CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
+            return CA_STATUS_OK;
+        }
+        else
+        {
+            CADestroyData(data, sizeof(CAData_t));
+        }
+        return res;
+    }
+    else
+#endif
+    {
+        CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
     }
+#endif
 
-    return -1;
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
 }
 
-int32_t CADetachResponseMessage(const CARemoteEndpoint_t* object, const CAResponseInfo_t* response)
+CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
+                                   const CAResponseInfo_t *response)
 {
-    OIC_LOG_V(DEBUG, TAG, "CADetachResponseMessage");
+    OIC_LOG(DEBUG, TAG, "IN");
+    VERIFY_NON_NULL(object, TAG, "object");
+    VERIFY_NON_NULL(response, TAG, "response");
 
-    if (object == NULL || response == NULL)
+    if (false == CAIsSelectedNetworkAvailable())
     {
-        return -1;
+        return CA_STATUS_FAILED;
     }
 
-    int32_t id = 0;
+    CAData_t *data = CAPrepareSendData(object, response, CA_RESPONSE_DATA);
+    if(!data)
+    {
+        OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
 
-    // create action id
-    id = CAIncreaseActionId();
+#ifdef SINGLE_THREAD
+    CAResult_t result = CAProcessSendData(data);
+    if(result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
+        return result;
+    }
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
-    MEMORY_ALLOCK_CHECK(data);
+    CADestroyData(data, sizeof(CAData_t));
+#else
+#ifdef WITH_BWT
+    if (CA_ADAPTER_GATT_BTLE != object->adapter
+#ifdef TCP_ADAPTER
+            && CA_ADAPTER_TCP != object->adapter
+#endif
+            )
+    {
+        // send block data
+        CAResult_t res = CASendBlockWiseData(data);
+        if(CA_NOT_SUPPORTED == res)
+        {
+            OIC_LOG(DEBUG, TAG, "normal msg will be sent");
+            CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
+            return CA_STATUS_OK;
+        }
+        else
+        {
+            CADestroyData(data, sizeof(CAData_t));
+        }
+        return res;
+    }
+    else
+#endif
+    {
+        CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
+    }
+#endif
 
-    // initialize
-    memset(data, 0, sizeof(CAData_t));
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
 
-    // clone remote endpoint
-    CARemoteEndpoint_t* remoteEndpoint = CACloneRemoteEndpoint(object);
-    MEMORY_ALLOCK_CHECK(remoteEndpoint);
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
+                                      uint8_t tokenLength, const CAHeaderOption_t *options,
+                                      uint8_t numOptions)
+{
+    (void)resourceUri;
+    (void)token;
+    (void)tokenLength;
+    (void)options;
+    (void)numOptions;
+    return CA_NOT_SUPPORTED;
+}
 
-    // clone response info
-    CAResponseInfo_t* responseInfo = CACloneResponseInfo(response);
-    MEMORY_ALLOCK_CHECK(responseInfo);
+void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
+                             CAErrorCallback errorHandler)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    g_requestHandler = ReqHandler;
+    g_responseHandler = RespHandler;
+    g_errorHandler = errorHandler;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
 
-    // save data
-    data->actionId = id;
-    data->remoteEndpoint = remoteEndpoint;
-    data->requestInfo = NULL;
-    data->responseInfo = responseInfo;
+CAResult_t CAInitializeMessageHandler()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CASetPacketReceivedCallback(CAReceivedPacketCallback);
 
-    // add thread
-    CAAddSendData(data);
+    CASetNetworkChangeCallback(CANetworkChangedCallback);
+    CASetErrorHandleCallback(CAErrorHandler);
 
-    return id;
+#ifndef SINGLE_THREAD
+    // create thread pool
+    CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
 
-    // memory error label.
-    memory_error_exit:
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool initialize error.");
+        return res;
+    }
 
-    CADestroyRemoteEndpointInternal(remoteEndpoint);
+    // send thread initialize
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
+                                                   CASendThreadProcess, CADestroyData))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
+        return CA_STATUS_FAILED;
+    }
 
-    CADestroyResponseInfoInternal(responseInfo);
+    // start send thread
+    res = CAQueueingThreadStart(&g_sendThread);
 
-    if (data != NULL)
+    if (CA_STATUS_OK != res)
     {
-        OICFree(data);
+        OIC_LOG(ERROR, TAG, "thread start error(send thread).");
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
+        return res;
     }
 
-    return -1;
-}
+    // receive thread initialize
+    if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
+                                                   CAReceiveThreadProcess, CADestroyData))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
+        return CA_STATUS_FAILED;
+    }
 
-int32_t CADetachMessageResourceUri(const CAURI_t resourceUri)
-{
-    if (resourceUri == NULL)
+#ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
+    // start receive thread
+    res = CAQueueingThreadStart(&gReceiveThread);
+
+    if (res != CA_STATUS_OK)
     {
-        return -1;
+        OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
+        return res;
     }
+#endif /* SINGLE_HANDLE */
+
+    // retransmission initialize
+    CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
+                               CATimeoutCallback, NULL);
 
-    int32_t id = 0;
+#ifdef WITH_BWT
+    // block-wise transfer initialize
+    CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
+#endif
 
-    // create action id
-    id = CAIncreaseActionId();
+    // start retransmission
+    res = CARetransmissionStart(&g_retransmissionContext);
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
-    MEMORY_ALLOCK_CHECK(data);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
+        return res;
+    }
+
+    // initialize interface adapters by controller
+    CAInitializeAdapters(g_threadPoolHandle);
+#else
+    // retransmission initialize
+    CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
+                               CATimeoutCallback, NULL);
+    CAInitializeAdapters();
+#endif
 
-    // initialize
-    memset(data, 0, sizeof(CAData_t));
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
 
-    CAAddress_t addr;
-    memset(&addr, 0, sizeof(CAAddress_t));
-    CARemoteEndpoint_t* remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
-            CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
+void CATerminateMessageHandler()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+#ifndef SINGLE_THREAD
+    CATransportAdapter_t connType;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+    uint32_t length = u_arraylist_length(list);
+
+    uint32_t i = 0;
+    for (i = 0; i < length; i++)
+    {
+        void* ptrType = u_arraylist_get(list, i);
 
-    // save data
-    data->actionId = id;
-    data->remoteEndpoint = remoteEndpoint;
-    data->requestInfo = NULL;
-    data->responseInfo = NULL;
+        if (NULL == ptrType)
+        {
+            continue;
+        }
 
-    // add thread
-    CAAddSendData(data);
+        connType = *(CATransportAdapter_t *)ptrType;
+        CAStopAdapter(connType);
+    }
 
-    return id;
+    // stop retransmission
+    if (NULL != g_retransmissionContext.threadMutex)
+    {
+        CARetransmissionStop(&g_retransmissionContext);
+    }
 
-    // memory error label.
-    memory_error_exit:
+    // stop thread
+    // delete thread data
+    if (NULL != g_sendThread.threadMutex)
+    {
+        CAQueueingThreadStop(&g_sendThread);
+    }
 
-    CADestroyRemoteEndpointInternal(remoteEndpoint);
+    // stop thread
+    // delete thread data
+    if (NULL != g_receiveThread.threadMutex)
+    {
+#ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
+        CAQueueingThreadStop(&gReceiveThread);
+#endif /* SINGLE_HANDLE */
+    }
 
-    if (data != NULL)
+    // destroy thread pool
+    if (NULL != g_threadPoolHandle)
     {
-        OICFree(data);
+        ca_thread_pool_free(g_threadPoolHandle);
+        g_threadPoolHandle = NULL;
     }
 
-    return -1;
-}
+#ifdef WITH_BWT
+    CATerminateBlockWiseTransfer();
+#endif
+    CARetransmissionDestroy(&g_retransmissionContext);
+    CAQueueingThreadDestroy(&g_sendThread);
+    CAQueueingThreadDestroy(&g_receiveThread);
 
-void CASetMessageHandlerCallback(CAMessageHandlerCallback callback)
-{
-    OIC_LOG_V(DEBUG, TAG, "set message handler callback.");
+    // terminate interface adapters by controller
+    CATerminateAdapters();
+#else
+    // terminate interface adapters by controller
+    CATerminateAdapters();
 
-    gHandlerCallback = callback;
+    // stop retransmission
+    CARetransmissionStop(&g_retransmissionContext);
+    CARetransmissionDestroy(&g_retransmissionContext);
+#endif
+
+    OIC_LOG(DEBUG, TAG, "OUT");
 }
 
-void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
+void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
 {
-    OIC_LOG_V(DEBUG, TAG, "set request, response handler callback.");
+    VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
+
+    OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
+
+#ifdef TCP_ADAPTER
+    if (CA_ADAPTER_TCP == endpoint->adapter)
+    {
+        OIC_LOG(DEBUG, TAG, "pdu header data :");
+        OIC_LOG_BUFFER(DEBUG, TAG,  pdu->hdr, pdu->length);
+    }
+    else
+#endif
+    {
+        OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
+
+        OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
 
-    gRequestHandler = ReqHandler;
-    gResponseHandler = RespHandler;
+        OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
+
+        OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
+                       pdu->hdr->coap_hdr_udp_t.token_length);
+    }
 }
 
-CAResult_t CAInitializeMessageHandler()
+static void CALogPayloadInfo(CAInfo_t *info)
 {
-    CASetPacketReceivedCallback(CAReceivedPacketCallback);
+    if(info)
+    {
+        if (info->options)
+        {
+            for (uint32_t i = 0; i < info->numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG, "optionID: %d", info->options[i].optionID);
 
-    // create thread pool
-    CAResult_t res;
-    res = u_thread_pool_init(MAX_THREAD_POOL_SIZE, &gThreadPoolHandle);
+                OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
+            }
+        }
 
-    if (res != CA_STATUS_OK)
+        if (info->payload)
+        {
+            OIC_LOG_V(DEBUG, TAG, "payload: %p(%u)", info->payload,
+                      info->payloadSize);
+        }
+
+        if (info->token)
+        {
+            OIC_LOG(DEBUG, TAG, "token:");
+            OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
+                           info->tokenLength);
+        }
+        OIC_LOG_V(DEBUG, TAG, "msgID: %d", info->messageId);
+    }
+    else
     {
-        OIC_LOG_V(DEBUG, TAG, "thread pool initialize error.");
-        return res;
+        OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
     }
+}
 
-    // send thread initialize
-    memset(&gSendThread, 0, sizeof(CAThread_t));
+void CAErrorHandler(const CAEndpoint_t *endpoint,
+                    const void *data, uint32_t dataLen,
+                    CAResult_t result)
+{
+    OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
 
-    // mutex init
-    u_mutex_init();
+#ifndef SINGLE_THREAD
 
-    // set send thread data
-    gSendThread.dataQueue = u_queue_create();
-    gSendThread.threadMutex = u_mutex_new();
-    gSendThread.threadCond = u_cond_new();
-    gSendThread.isStop = FALSE;
-    gSendThread.threadTask = CASendThreadProcess;
+    VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
+    VERIFY_NON_NULL_VOID(data, TAG, "data");
 
-    // start send thread
-    res = u_thread_pool_add_task(gThreadPoolHandle, CAThreadBaseRoutine, &gSendThread);
+    uint32_t code = CA_NOT_FOUND;
+    //Do not free remoteEndpoint and data. Currently they will be freed in data thread
+    //Get PDU data
+    coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
+    if (NULL == pdu)
+    {
+        OIC_LOG(ERROR, TAG, "Parse PDU failed");
+        return;
+    }
 
-    if (res != CA_STATUS_OK)
+    CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
+    if(!cadata)
     {
-        OIC_LOG_V(DEBUG, TAG, "thread pool add task error.");
-        return res;
+        OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
+        coap_delete_pdu(pdu);
+        return;
     }
 
-    // set receive queue
-    gMessageQueue = u_queue_create();
-    gMessageQueueMutex = u_mutex_new();
+    cadata->errorInfo->result = result;
 
-    // initialize interface adapters by controller
-    CAInitializeAdapters();
+    CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+    coap_delete_pdu(pdu);
+#endif
 
-    return CA_STATUS_OK;
+    OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
+    return;
 }
 
-void CATerminateMessageHandler()
+static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
 {
-    // terminate interface adapters by controller
-    CATerminateAdapters();
+    OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
+#ifndef SINGLE_THREAD
+    CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+    if (!cadata)
+    {
+        OIC_LOG(ERROR, TAG, "memory allocation failed");
+        return;
+    }
 
-    // stop thread
-    CAStopSendThread();
+    CAEndpoint_t* ep = CACloneEndpoint(endpoint);
+    if (!ep)
+    {
+        OIC_LOG(ERROR, TAG, "endpoint clone failed");
+        OICFree(cadata);
+        return;
+    }
 
-    // delete thread data
-    u_mutex_free(gSendThread.threadMutex);
-    u_cond_free(gSendThread.threadCond);
-    u_queue_delete(gSendThread.dataQueue);
+    CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
+    if (!errorInfo)
+    {
+        OICFree(cadata);
+        CAFreeEndpoint(ep);
+        return;
+    }
 
-    // destroy thread pool
-    u_thread_pool_free(gThreadPoolHandle);
+    CAResult_t res = CACloneInfo(info, &errorInfo->info);
+    if (CA_STATUS_OK != res)
+    {
+        OICFree(cadata);
+        CAFreeEndpoint(ep);
+        return;
+    }
 
-    OIC_LOG_V(DEBUG, TAG, "message handler terminate completed!");
+    errorInfo->result = result;
+    cadata->remoteEndpoint = ep;
+    cadata->errorInfo = errorInfo;
+    cadata->dataType = CA_ERROR_DATA;
 
-    u_queue_delete(gMessageQueue);
-    u_mutex_free(gMessageQueueMutex);
+    CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+#endif
+    OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
 }
-