2d17312f1b779cd706d42cd83736d90825e7198e
[iotivity.git] / resource / csdk / connectivity / src / camessagehandler.c
1 /* *****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdint.h>
25
26 #include "cainterface.h"
27 #include "camessagehandler.h"
28 #include "caremotehandler.h"
29 #include "caprotocolmessage.h"
30 #include "logger.h"
31 #include "config.h" /* for coap protocol */
32 #include "oic_malloc.h"
33 #include "canetworkconfigurator.h"
34 #include "caadapterutils.h"
35 #include "cainterfacecontroller.h"
36 #include "caretransmission.h"
37 #include "oic_string.h"
38
39 #ifdef WITH_BWT
40 #include "cablockwisetransfer.h"
41 #endif
42
43 #ifndef  SINGLE_THREAD
44 #include "uqueue.h"
45 #include "cathreadpool.h" /* for thread pool */
46 #include "caqueueingthread.h"
47
48 #define SINGLE_HANDLE
49 #define MAX_THREAD_POOL_SIZE    20
50
51 // thread pool handle
52 static ca_thread_pool_t g_threadPoolHandle = NULL;
53
54 // message handler main thread
55 static CAQueueingThread_t g_sendThread;
56 static CAQueueingThread_t g_receiveThread;
57
58 #else
59 #define CA_MAX_RT_ARRAY_SIZE    3
60 #endif  // SINGLE_THREAD
61
62 #define TAG "OIC_CA_MSG_HANDLE"
63
64 static CARetransmission_t g_retransmissionContext;
65
66 // handler field
67 static CARequestCallback g_requestHandler = NULL;
68 static CAResponseCallback g_responseHandler = NULL;
69 static CAErrorCallback g_errorHandler = NULL;
70 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
71
72 static void CAErrorHandler(const CAEndpoint_t *endpoint,
73                            const void *data, uint32_t dataLen,
74                            CAResult_t result);
75
76 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
77                                        const CARemoteId_t *identity,
78                                        const void *data, CADataType_t dataType);
79
80 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
81                             CAResult_t result);
82
83 #ifdef SINGLE_THREAD
84 static void CAProcessReceivedData(CAData_t *data);
85 #endif
86 static void CADestroyData(void *data, uint32_t size);
87 static void CALogPayloadInfo(CAInfo_t *info);
88 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
89                                 CAToken_t token, uint8_t tokenLength);
90
91 #ifdef WITH_BWT
92 void CAAddDataToSendThread(CAData_t *data)
93 {
94     VERIFY_NON_NULL_VOID(data, TAG, "data");
95
96     // add thread
97     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
98 }
99
100 void CAAddDataToReceiveThread(CAData_t *data)
101 {
102     VERIFY_NON_NULL_VOID(data, TAG, "data");
103
104     // add thread
105     CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
106 }
107 #endif
108
109 static bool CAIsSelectedNetworkAvailable()
110 {
111     u_arraylist_t *list = CAGetSelectedNetworkList();
112     if (!list || u_arraylist_length(list) == 0)
113     {
114         OIC_LOG(ERROR, TAG, "No selected network");
115         return false;
116     }
117
118     return true;
119 }
120
121 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
122                                        const CARemoteId_t *identity,
123                                        const void *data, CADataType_t dataType)
124 {
125     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
126     CAInfo_t *info = NULL;
127     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
128     if (!cadata)
129     {
130         OIC_LOG(ERROR, TAG, "memory allocation failed");
131         return NULL;
132     }
133
134     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
135     if (!ep)
136     {
137         OIC_LOG(ERROR, TAG, "endpoint clone failed");
138         OICFree(cadata);
139         return NULL;
140     }
141
142     OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
143
144     if(CA_RESPONSE_DATA == dataType)
145     {
146         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
147         if (!resInfo)
148         {
149             OIC_LOG(ERROR, TAG, "memory allocation failed");
150             OICFree(cadata);
151             CAFreeEndpoint(ep);
152             return NULL;
153         }
154
155         CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
156         if (CA_STATUS_OK != result)
157         {
158             OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
159             CAFreeEndpoint(ep);
160             CADestroyResponseInfoInternal(resInfo);
161             OICFree(cadata);
162             return NULL;
163         }
164         cadata->responseInfo = resInfo;
165         info = &resInfo->info;
166         if (identity)
167         {
168             info->identity = *identity;
169         }
170         OIC_LOG(DEBUG, TAG, "Response Info :");
171         CALogPayloadInfo(info);
172     }
173     else if (CA_REQUEST_DATA == dataType)
174     {
175         CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
176         if (!reqInfo)
177         {
178             OIC_LOG(ERROR, TAG, "memory allocation failed");
179             OICFree(cadata);
180             CAFreeEndpoint(ep);
181             return NULL;
182         }
183
184         CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
185         if (CA_STATUS_OK != result)
186         {
187             OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
188             CAFreeEndpoint(ep);
189             CADestroyRequestInfoInternal(reqInfo);
190             OICFree(cadata);
191             return NULL;
192         }
193
194         if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
195                                 reqInfo->info.token, reqInfo->info.tokenLength))
196         {
197             OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
198             CAFreeEndpoint(ep);
199             CADestroyRequestInfoInternal(reqInfo);
200             OICFree(cadata);
201             return NULL;
202         }
203
204         cadata->requestInfo = reqInfo;
205         info = &reqInfo->info;
206         if (identity)
207         {
208             info->identity = *identity;
209         }
210         OIC_LOG(DEBUG, TAG, "Request Info :");
211         CALogPayloadInfo(info);
212    }
213     else if (CA_ERROR_DATA == dataType)
214     {
215         CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
216         if (!errorInfo)
217         {
218             OIC_LOG(ERROR, TAG, "Memory allocation failed!");
219             OICFree(cadata);
220             CAFreeEndpoint(ep);
221             return NULL;
222         }
223
224         CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
225         if (CA_STATUS_OK != result)
226         {
227             OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
228             CAFreeEndpoint(ep);
229             OICFree(errorInfo);
230             OICFree(cadata);
231             return NULL;
232         }
233
234         cadata->errorInfo = errorInfo;
235         info = &errorInfo->info;
236         if (identity)
237         {
238             info->identity = *identity;
239         }
240         OIC_LOG(DEBUG, TAG, "error Info :");
241         CALogPayloadInfo(info);
242     }
243
244     cadata->remoteEndpoint = ep;
245     cadata->dataType = dataType;
246
247     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
248     return cadata;
249 }
250
251 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
252 {
253     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
254     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
255
256     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
257     if (!ep)
258     {
259         OIC_LOG(ERROR, TAG, "clone failed");
260         return;
261     }
262
263     CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
264
265     if (!resInfo)
266     {
267         OIC_LOG(ERROR, TAG, "calloc failed");
268         CAFreeEndpoint(ep);
269         return;
270     }
271
272     resInfo->result = CA_RETRANSMIT_TIMEOUT;
273     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
274     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
275
276     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
277                                        endpoint);
278     if (CA_STATUS_OK != res)
279     {
280         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
281         CADestroyResponseInfoInternal(resInfo);
282         CAFreeEndpoint(ep);
283         return;
284     }
285
286     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
287     if (NULL == cadata)
288     {
289         OIC_LOG(ERROR, TAG, "memory allocation failed !");
290         CAFreeEndpoint(ep);
291         CADestroyResponseInfoInternal(resInfo);
292         return;
293     }
294
295     cadata->type = SEND_TYPE_UNICAST;
296     cadata->remoteEndpoint = ep;
297     cadata->requestInfo = NULL;
298     cadata->responseInfo = resInfo;
299
300 #ifdef WITH_BWT
301     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
302     {
303         res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
304                                                 endpoint->port);
305         if (CA_STATUS_OK != res)
306         {
307             OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
308         }
309     }
310 #endif // WITH_BWT
311
312 #ifdef SINGLE_THREAD
313     CAProcessReceivedData(cadata);
314 #else
315     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
316 #endif
317 }
318
319 static void CADestroyData(void *data, uint32_t size)
320 {
321     OIC_LOG(DEBUG, TAG, "CADestroyData IN");
322     if ((size_t)size < sizeof(CAData_t))
323     {
324         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
325     }
326     CAData_t *cadata = (CAData_t *) data;
327
328     if (NULL == cadata)
329     {
330         OIC_LOG(ERROR, TAG, "cadata is NULL");
331         return;
332     }
333
334     if (NULL != cadata->remoteEndpoint)
335     {
336         CAFreeEndpoint(cadata->remoteEndpoint);
337     }
338
339     if (NULL != cadata->requestInfo)
340     {
341         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
342     }
343
344     if (NULL != cadata->responseInfo)
345     {
346         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
347     }
348
349     if (NULL != cadata->errorInfo)
350     {
351         CADestroyErrorInfoInternal(cadata->errorInfo);
352     }
353
354     OICFree(cadata);
355     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
356 }
357
358 #ifdef SINGLE_THREAD
359 static void CAProcessReceivedData(CAData_t *data)
360 {
361     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
362     if (!data)
363     {
364         OIC_LOG(ERROR, TAG, "thread data error!!");
365         return;
366     }
367
368     // parse the data and call the callbacks.
369     // #1 parse the data
370     // #2 get endpoint
371     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
372     if (!rep)
373     {
374         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
375         return;
376     }
377
378     if (data->requestInfo && g_requestHandler)
379     {
380         g_requestHandler(rep, data->requestInfo);
381     }
382     else if (data->responseInfo && g_responseHandler)
383     {
384         g_responseHandler(rep, data->responseInfo);
385     }
386     else if (data->errorInfo && g_errorHandler)
387     {
388         g_errorHandler(rep, data->errorInfo);
389     }
390
391     CADestroyData(data, sizeof(CAData_t));
392
393     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
394 }
395 #endif
396
397 #ifndef SINGLE_THREAD
398 static void CAReceiveThreadProcess(void *threadData)
399 {
400 #ifndef SINGLE_HANDLE
401     CAData_t *data = (CAData_t *) threadData;
402     CAProcessReceivedData(data);
403 #else
404     (void)threadData;
405 #endif
406 }
407 #endif // SINGLE_THREAD
408
409 static CAResult_t CAProcessMulticastData(const CAData_t *data)
410 {
411     VERIFY_NON_NULL(data, TAG, "data");
412     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
413
414     coap_pdu_t *pdu = NULL;
415     CAInfo_t *info = NULL;
416     coap_list_t *options = NULL;
417     coap_transport_type transport = coap_udp;
418     CAResult_t res = CA_SEND_FAILED;
419     if (NULL != data->requestInfo)
420     {
421         OIC_LOG(DEBUG, TAG, "requestInfo is available..");
422
423         info = &data->requestInfo->info;
424         pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
425
426         if (NULL != pdu)
427         {
428 #ifdef WITH_BWT
429             if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
430             {
431                 // Blockwise transfer
432                 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
433                 if (CA_STATUS_OK != res)
434                 {
435                     OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
436                     goto exit;
437                 }
438             }
439 #endif // WITH_BWT
440         }
441         else
442         {
443             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
444             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
445             return res;
446         }
447     }
448     else if (NULL != data->responseInfo)
449     {
450         OIC_LOG(DEBUG, TAG, "responseInfo is available..");
451
452         info = &data->responseInfo->info;
453         pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
454                             &options, &transport);
455
456         if (NULL != pdu)
457         {
458 #ifdef WITH_BWT
459             if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
460             {
461                 // Blockwise transfer
462                 if (NULL != info)
463                 {
464                     res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
465                     if (CA_STATUS_OK != res)
466                     {
467                         OIC_LOG(INFO, TAG, "to write block option has failed");
468                         goto exit;
469                     }
470                 }
471             }
472 #endif // WITH_BWT
473         }
474         else
475         {
476             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
477             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
478             return res;
479         }
480     }
481     else
482     {
483         OIC_LOG(ERROR, TAG, "request or response info is empty");
484         return res;
485     }
486
487     CALogPDUInfo(pdu, data->remoteEndpoint);
488
489     OIC_LOG(DEBUG, TAG, "pdu to send :");
490     OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->hdr, pdu->length);
491
492     res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
493     if (CA_STATUS_OK != res)
494     {
495         OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
496         goto exit;
497     }
498
499     coap_delete_list(options);
500     coap_delete_pdu(pdu);
501     return res;
502
503 exit:
504     CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
505     coap_delete_list(options);
506     coap_delete_pdu(pdu);
507     return res;
508 }
509
510 static CAResult_t CAProcessSendData(const CAData_t *data)
511 {
512     VERIFY_NON_NULL(data, TAG, "data");
513     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
514
515     CAResult_t res = CA_STATUS_FAILED;
516
517     CASendDataType_t type = data->type;
518
519     coap_pdu_t *pdu = NULL;
520     CAInfo_t *info = NULL;
521     coap_list_t *options = NULL;
522     coap_transport_type transport = coap_udp;
523
524     if (SEND_TYPE_UNICAST == type)
525     {
526         OIC_LOG(DEBUG,TAG,"Unicast message");
527
528 #ifdef ROUTING_GATEWAY
529         /*
530          * When forwarding a packet, do not attempt retransmission as its the responsibility of
531          * packet originator node
532          */
533         bool skipRetransmission = false;
534 #endif
535
536         if (NULL != data->requestInfo)
537         {
538             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
539
540             info = &data->requestInfo->info;
541 #ifdef ROUTING_GATEWAY
542             skipRetransmission = data->requestInfo->info.skipRetransmission;
543 #endif
544             pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
545                                 &options, &transport);
546         }
547         else if (NULL != data->responseInfo)
548         {
549             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
550
551             info = &data->responseInfo->info;
552 #ifdef ROUTING_GATEWAY
553             skipRetransmission = data->responseInfo->info.skipRetransmission;
554 #endif
555             pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
556                                 &options, &transport);
557         }
558         else
559         {
560             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
561             return CA_STATUS_INVALID_PARAM;
562         }
563
564         // interface controller function call.
565         if (NULL != pdu)
566         {
567 #ifdef WITH_BWT
568             if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
569             {
570                 // Blockwise transfer
571                 if (NULL != info)
572                 {
573                     CAResult_t res = CAAddBlockOption(&pdu, info,
574                                                       data->remoteEndpoint,
575                                                       &options);
576                     if (CA_STATUS_OK != res)
577                     {
578                         OIC_LOG(INFO, TAG, "to write block option has failed");
579                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
580                         coap_delete_list(options);
581                         coap_delete_pdu(pdu);
582                         return res;
583                     }
584                 }
585             }
586 #endif // WITH_BWT
587             CALogPDUInfo(pdu, data->remoteEndpoint);
588
589             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
590             if (CA_STATUS_OK != res)
591             {
592                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
593                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
594                 coap_delete_list(options);
595                 coap_delete_pdu(pdu);
596                 return res;
597             }
598
599 #ifdef WITH_TCP
600             if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
601             {
602                 OIC_LOG(INFO, TAG, "retransmission will be not worked");
603             }
604             else
605 #endif
606 #ifdef ROUTING_GATEWAY
607             if(!skipRetransmission)
608 #endif
609             {
610                 // for retransmission
611                 res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint,
612                                                pdu->hdr, pdu->length);
613                 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
614                 {
615                     //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
616                     OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
617                     coap_delete_list(options);
618                     coap_delete_pdu(pdu);
619                     return res;
620                 }
621             }
622
623             coap_delete_list(options);
624             coap_delete_pdu(pdu);
625         }
626         else
627         {
628             OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
629             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
630             return CA_SEND_FAILED;
631         }
632     }
633     else if (SEND_TYPE_MULTICAST == type)
634     {
635         OIC_LOG(DEBUG,TAG,"Multicast message");
636 #ifdef WITH_TCP
637         /*
638          * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
639          * That's why we need to generate two pdu's, one for IP and second for other transports.
640          * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
641          * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
642          */
643         if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
644                 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
645                     CA_ADAPTER_IP != data->remoteEndpoint->adapter))
646         {
647             if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
648             {
649                 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
650             }
651             else
652             {
653                 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
654             }
655             CAProcessMulticastData(data);
656             data->remoteEndpoint->adapter = CA_ADAPTER_IP;
657             CAProcessMulticastData(data);
658         }
659         else
660         {
661             CAProcessMulticastData(data);
662         }
663 #else
664         CAProcessMulticastData(data);
665 #endif
666     }
667
668     return CA_STATUS_OK;
669 }
670
671 #ifndef SINGLE_THREAD
672 static void CASendThreadProcess(void *threadData)
673 {
674     CAData_t *data = (CAData_t *) threadData;
675     CAProcessSendData(data);
676 }
677 #endif
678
679 /*
680  * If a second message arrives with the same message ID, token and the other address
681  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
682  */
683 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
684                                 CAToken_t token, uint8_t tokenLength)
685 {
686     if (!ep)
687     {
688         return true;
689     }
690     if (ep->adapter != CA_ADAPTER_IP)
691     {
692         return false;
693     }
694     if (!caglobals.ip.dualstack)
695     {
696         return false;
697     }
698
699     if (tokenLength > CA_MAX_TOKEN_LEN)
700     {
701         /*
702          * If token length is more than CA_MAX_TOKEN_LEN,
703          * we compare the first CA_MAX_TOKEN_LEN bytes only.
704          */
705         tokenLength = CA_MAX_TOKEN_LEN;
706     }
707
708     bool ret = false;
709     CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
710
711     for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
712     {
713         CAHistoryItem_t *item = &(history->items[i]);
714         if (id == item->messageId && tokenLength == item->tokenLength
715             && memcmp(item->token, token, tokenLength) == 0)
716         {
717             if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
718             {
719                 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
720                           familyFlags & CA_IPV6 ? '6' : '4');
721                 ret = true;
722                 break;
723             }
724         }
725     }
726
727     history->items[history->nextIndex].flags = familyFlags;
728     history->items[history->nextIndex].messageId = id;
729     if (token && tokenLength)
730     {
731         memcpy(history->items[history->nextIndex].token, token, tokenLength);
732         history->items[history->nextIndex].tokenLength = tokenLength;
733     }
734
735     if (++history->nextIndex >= HISTORYSIZE)
736     {
737         history->nextIndex = 0;
738     }
739
740     return ret;
741 }
742
743 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
744                                      const void *data, uint32_t dataLen)
745 {
746     VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
747     VERIFY_NON_NULL_VOID(data, TAG, "data");
748
749     OIC_LOG(DEBUG, TAG, "received pdu data :");
750     OIC_LOG_BUFFER(DEBUG, TAG,  data, dataLen);
751
752     uint32_t code = CA_NOT_FOUND;
753     CAData_t *cadata = NULL;
754
755     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
756                                                 &(sep->endpoint));
757     if (NULL == pdu)
758     {
759         OIC_LOG(ERROR, TAG, "Parse PDU failed");
760         return;
761     }
762
763     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
764     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
765     {
766         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
767         if (!cadata)
768         {
769             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
770             coap_delete_pdu(pdu);
771             return;
772         }
773     }
774     else
775     {
776         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
777         if (!cadata)
778         {
779             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
780             coap_delete_pdu(pdu);
781             return;
782         }
783
784 #ifdef WITH_TCP
785         if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
786         {
787             OIC_LOG(INFO, TAG, "retransmission is not supported");
788         }
789         else
790 #endif
791         {
792             // for retransmission
793             void *retransmissionPdu = NULL;
794             CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
795                                          pdu->length, &retransmissionPdu);
796
797             // get token from saved data in retransmission list
798             if (retransmissionPdu && CA_EMPTY == code)
799             {
800                 if (cadata->responseInfo)
801                 {
802                     CAInfo_t *info = &cadata->responseInfo->info;
803                     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
804                                                        info, &(sep->endpoint));
805                     if (CA_STATUS_OK != res)
806                     {
807                         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
808                         OICFree(info->token);
809                         info->tokenLength = 0;
810                     }
811                 }
812             }
813             OICFree(retransmissionPdu);
814         }
815     }
816
817     cadata->type = SEND_TYPE_UNICAST;
818
819 #ifdef SINGLE_THREAD
820     CAProcessReceivedData(cadata);
821 #else
822 #ifdef WITH_BWT
823     if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
824     {
825         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
826         if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
827         {
828             OIC_LOG(DEBUG, TAG, "this message does not have block option");
829             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
830         }
831         else
832         {
833             CADestroyData(cadata, sizeof(CAData_t));
834         }
835     }
836     else
837 #endif
838     {
839         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
840     }
841 #endif // SINGLE_THREAD
842
843     coap_delete_pdu(pdu);
844 }
845
846 void CAHandleRequestResponseCallbacks()
847 {
848 #ifdef SINGLE_THREAD
849     CAReadData();
850     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
851 #else
852 #ifdef SINGLE_HANDLE
853     // parse the data and call the callbacks.
854     // #1 parse the data
855     // #2 get endpoint
856
857     ca_mutex_lock(g_receiveThread.threadMutex);
858
859     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
860
861     ca_mutex_unlock(g_receiveThread.threadMutex);
862
863     if (NULL == item || NULL == item->msg)
864     {
865         return;
866     }
867
868     // get endpoint
869     CAData_t *td = (CAData_t *) item->msg;
870
871     if (td->requestInfo && g_requestHandler)
872     {
873         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
874         g_requestHandler(td->remoteEndpoint, td->requestInfo);
875     }
876     else if (td->responseInfo && g_responseHandler)
877     {
878         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
879         g_responseHandler(td->remoteEndpoint, td->responseInfo);
880     }
881     else if (td->errorInfo && g_errorHandler)
882     {
883         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
884         g_errorHandler(td->remoteEndpoint, td->errorInfo);
885     }
886
887     CADestroyData(item->msg, sizeof(CAData_t));
888     OICFree(item);
889
890 #endif // SINGLE_HANDLE
891 #endif // SINGLE_THREAD
892 }
893
894 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
895                                    CADataType_t dataType)
896 {
897     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
898
899     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
900     if (!cadata)
901     {
902         OIC_LOG(ERROR, TAG, "memory allocation failed");
903         return NULL;
904     }
905
906     if(CA_REQUEST_DATA == dataType)
907     {
908         // clone request info
909         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
910
911         if(!request)
912         {
913             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
914             goto exit;
915         }
916
917         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
918         cadata->requestInfo =  request;
919     }
920     else if(CA_RESPONSE_DATA == dataType)
921     {
922         // clone response info
923         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
924
925         if(!response)
926         {
927             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
928             goto exit;
929         }
930
931         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
932         cadata->responseInfo = response;
933     }
934     else
935     {
936         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
937         goto exit;
938     }
939
940     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
941     if (!ep)
942     {
943         OIC_LOG(ERROR, TAG, "endpoint clone failed");
944         CADestroyData(cadata, sizeof(CAData_t));
945         return NULL;
946     }
947
948     cadata->remoteEndpoint = ep;
949     cadata->dataType = dataType;
950     return cadata;
951
952 exit:
953     OICFree(cadata);
954     return NULL;
955 }
956
957 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
958                                CADataType_t dataType)
959 {
960     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
961     VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
962
963     if (false == CAIsSelectedNetworkAvailable())
964     {
965         return CA_STATUS_FAILED;
966     }
967
968 #ifdef ARDUINO
969     // If max retransmission queue is reached, then don't handle new request
970     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
971     {
972         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
973         return CA_SEND_FAILED;
974     }
975 #endif // ARDUINO
976
977     CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
978     if(!data)
979     {
980         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
981         return CA_MEMORY_ALLOC_FAILED;
982     }
983
984 #ifdef SINGLE_THREAD
985     CAResult_t result = CAProcessSendData(data);
986     if(CA_STATUS_OK != result)
987     {
988         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
989         CADestroyData(data, sizeof(CAData_t));
990         return result;
991     }
992
993     CADestroyData(data, sizeof(CAData_t));
994 #else
995 #ifdef WITH_BWT
996     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
997     {
998         // send block data
999         CAResult_t res = CASendBlockWiseData(data);
1000         if(CA_NOT_SUPPORTED == res)
1001         {
1002             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1003             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1004             return CA_STATUS_OK;
1005         }
1006         else
1007         {
1008             CADestroyData(data, sizeof(CAData_t));
1009         }
1010         return res;
1011     }
1012     else
1013 #endif // WITH_BWT
1014     {
1015         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1016     }
1017 #endif // SINGLE_THREAD
1018
1019     return CA_STATUS_OK;
1020 }
1021
1022 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1023                              CAErrorCallback errorHandler)
1024 {
1025     g_requestHandler = ReqHandler;
1026     g_responseHandler = RespHandler;
1027     g_errorHandler = errorHandler;
1028 }
1029
1030 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1031 {
1032     g_nwMonitorHandler = nwMonitorHandler;
1033 }
1034
1035 CAResult_t CAInitializeMessageHandler()
1036 {
1037     CASetPacketReceivedCallback(CAReceivedPacketCallback);
1038     CASetErrorHandleCallback(CAErrorHandler);
1039
1040 #ifndef SINGLE_THREAD
1041     // create thread pool
1042     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1043     if (CA_STATUS_OK != res)
1044     {
1045         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1046         return res;
1047     }
1048
1049     // send thread initialize
1050     res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1051                                      CASendThreadProcess, CADestroyData);
1052     if (CA_STATUS_OK != res)
1053     {
1054         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1055         ca_thread_pool_free(g_threadPoolHandle);
1056         g_threadPoolHandle = NULL;
1057         return res;
1058     }
1059
1060     // start send thread
1061     res = CAQueueingThreadStart(&g_sendThread);
1062     if (CA_STATUS_OK != res)
1063     {
1064         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1065         ca_thread_pool_free(g_threadPoolHandle);
1066         g_threadPoolHandle = NULL;
1067         CAQueueingThreadDestroy(&g_sendThread);
1068         return res;
1069     }
1070
1071     // receive thread initialize
1072     res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1073                                      CAReceiveThreadProcess, CADestroyData);
1074     if (CA_STATUS_OK != res)
1075     {
1076         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1077         ca_thread_pool_free(g_threadPoolHandle);
1078         g_threadPoolHandle = NULL;
1079         CAQueueingThreadDestroy(&g_sendThread);
1080         return res;
1081     }
1082
1083 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1084     // start receive thread
1085     res = CAQueueingThreadStart(&g_receiveThread);
1086     if (CA_STATUS_OK != res)
1087     {
1088         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1089         ca_thread_pool_free(g_threadPoolHandle);
1090         g_threadPoolHandle = NULL;
1091         CAQueueingThreadDestroy(&g_sendThread);
1092         CAQueueingThreadDestroy(&g_receiveThread);
1093         return res;
1094     }
1095 #endif // SINGLE_HANDLE
1096
1097     // retransmission initialize
1098     res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1099                                      CASendUnicastData, CATimeoutCallback, NULL);
1100     if (CA_STATUS_OK != res)
1101     {
1102         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1103         ca_thread_pool_free(g_threadPoolHandle);
1104         g_threadPoolHandle = NULL;
1105         CAQueueingThreadDestroy(&g_sendThread);
1106         CAQueueingThreadDestroy(&g_receiveThread);
1107         return res;
1108     }
1109
1110 #ifdef WITH_BWT
1111     // block-wise transfer initialize
1112     res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1113     if (CA_STATUS_OK != res)
1114     {
1115         OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1116         ca_thread_pool_free(g_threadPoolHandle);
1117         g_threadPoolHandle = NULL;
1118         CAQueueingThreadDestroy(&g_sendThread);
1119         CAQueueingThreadDestroy(&g_receiveThread);
1120         CARetransmissionDestroy(&g_retransmissionContext);
1121         return res;
1122     }
1123 #endif
1124
1125     // start retransmission
1126     res = CARetransmissionStart(&g_retransmissionContext);
1127     if (CA_STATUS_OK != res)
1128     {
1129         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1130         ca_thread_pool_free(g_threadPoolHandle);
1131         g_threadPoolHandle = NULL;
1132         CAQueueingThreadDestroy(&g_sendThread);
1133         CAQueueingThreadDestroy(&g_receiveThread);
1134         CARetransmissionDestroy(&g_retransmissionContext);
1135         return res;
1136     }
1137
1138     // initialize interface adapters by controller
1139     CAInitializeAdapters(g_threadPoolHandle);
1140 #else
1141     // retransmission initialize
1142     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1143                                                 CATimeoutCallback, NULL);
1144     if (CA_STATUS_OK != res)
1145     {
1146         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1147         return res;
1148     }
1149
1150     CAInitializeAdapters();
1151 #endif // SINGLE_THREAD
1152
1153     return CA_STATUS_OK;
1154 }
1155
1156 void CATerminateMessageHandler()
1157 {
1158 #ifndef SINGLE_THREAD
1159     CATransportAdapter_t connType;
1160     u_arraylist_t *list = CAGetSelectedNetworkList();
1161     uint32_t length = u_arraylist_length(list);
1162
1163     uint32_t i = 0;
1164     for (i = 0; i < length; i++)
1165     {
1166         void* ptrType = u_arraylist_get(list, i);
1167
1168         if (NULL == ptrType)
1169         {
1170             continue;
1171         }
1172
1173         connType = *(CATransportAdapter_t *)ptrType;
1174         CAStopAdapter(connType);
1175     }
1176
1177     // stop retransmission
1178     if (NULL != g_retransmissionContext.threadMutex)
1179     {
1180         CARetransmissionStop(&g_retransmissionContext);
1181     }
1182
1183     // stop thread
1184     // delete thread data
1185     if (NULL != g_sendThread.threadMutex)
1186     {
1187         CAQueueingThreadStop(&g_sendThread);
1188     }
1189
1190     // stop thread
1191     // delete thread data
1192     if (NULL != g_receiveThread.threadMutex)
1193     {
1194 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1195         CAQueueingThreadStop(&g_receiveThread);
1196 #endif
1197     }
1198
1199     // destroy thread pool
1200     if (NULL != g_threadPoolHandle)
1201     {
1202         ca_thread_pool_free(g_threadPoolHandle);
1203         g_threadPoolHandle = NULL;
1204     }
1205
1206 #ifdef WITH_BWT
1207     CATerminateBlockWiseTransfer();
1208 #endif
1209     CARetransmissionDestroy(&g_retransmissionContext);
1210     CAQueueingThreadDestroy(&g_sendThread);
1211     CAQueueingThreadDestroy(&g_receiveThread);
1212
1213     // terminate interface adapters by controller
1214     CATerminateAdapters();
1215 #else
1216     // terminate interface adapters by controller
1217     CATerminateAdapters();
1218
1219     // stop retransmission
1220     CARetransmissionStop(&g_retransmissionContext);
1221     CARetransmissionDestroy(&g_retransmissionContext);
1222 #endif // SINGLE_THREAD
1223 }
1224
1225 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1226 {
1227     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1228     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1229
1230     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1231
1232 #ifdef WITH_TCP
1233     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1234     {
1235         OIC_LOG(DEBUG, TAG, "pdu header data :");
1236         OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->hdr, pdu->length);
1237     }
1238     else
1239 #endif
1240     {
1241         OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1242
1243         OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1244
1245         OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1246
1247         OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1248                        pdu->hdr->coap_hdr_udp_t.token_length);
1249     }
1250 }
1251
1252 static void CALogPayloadInfo(CAInfo_t *info)
1253 {
1254     if(info)
1255     {
1256         if (info->options)
1257         {
1258             for (uint32_t i = 0; i < info->numOptions; i++)
1259             {
1260                 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1261
1262                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1263             }
1264         }
1265
1266         if (info->payload)
1267         {
1268             OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1269                       info->payloadSize);
1270         }
1271
1272         if (info->token)
1273         {
1274             OIC_LOG(DEBUG, TAG, "token:");
1275             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1276                            info->tokenLength);
1277         }
1278         OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1279     }
1280     else
1281     {
1282         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1283     }
1284 }
1285
1286 void CAErrorHandler(const CAEndpoint_t *endpoint,
1287                     const void *data, uint32_t dataLen,
1288                     CAResult_t result)
1289 {
1290     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1291
1292 #ifndef SINGLE_THREAD
1293     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1294     VERIFY_NON_NULL_VOID(data, TAG, "data");
1295
1296     uint32_t code = CA_NOT_FOUND;
1297     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1298     //Get PDU data
1299     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1300     if (NULL == pdu)
1301     {
1302         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1303         return;
1304     }
1305
1306     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1307     if(!cadata)
1308     {
1309         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1310         coap_delete_pdu(pdu);
1311         return;
1312     }
1313
1314     cadata->errorInfo->result = result;
1315
1316     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1317     coap_delete_pdu(pdu);
1318 #endif
1319
1320     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1321     return;
1322 }
1323
1324 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1325 {
1326     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1327 #ifndef SINGLE_THREAD
1328     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1329     if (!cadata)
1330     {
1331         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1332         return;
1333     }
1334
1335     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1336     if (!ep)
1337     {
1338         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1339         OICFree(cadata);
1340         return;
1341     }
1342
1343     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1344     if (!errorInfo)
1345     {
1346         OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1347         OICFree(cadata);
1348         CAFreeEndpoint(ep);
1349         return;
1350     }
1351
1352     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1353     if (CA_STATUS_OK != res)
1354     {
1355         OIC_LOG(ERROR, TAG, "info clone failed");
1356         OICFree(cadata);
1357         OICFree(errorInfo);
1358         CAFreeEndpoint(ep);
1359         return;
1360     }
1361
1362     errorInfo->result = result;
1363     cadata->remoteEndpoint = ep;
1364     cadata->errorInfo = errorInfo;
1365     cadata->dataType = CA_ERROR_DATA;
1366
1367     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1368 #endif
1369     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1370 }