Merge branch 'master' into notification-service
[platform/upstream/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     CAResult_t result;
144
145     if(CA_RESPONSE_DATA == dataType)
146     {
147         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
148         if (!resInfo)
149         {
150             OIC_LOG(ERROR, TAG, "memory allocation failed");
151             OICFree(cadata);
152             CAFreeEndpoint(ep);
153             return NULL;
154         }
155
156         result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
157         if (CA_STATUS_OK != result)
158         {
159             OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
160             CAFreeEndpoint(ep);
161             CADestroyResponseInfoInternal(resInfo);
162             OICFree(cadata);
163             return NULL;
164         }
165         cadata->responseInfo = resInfo;
166         info = &resInfo->info;
167         if (identity)
168         {
169             info->identity = *identity;
170         }
171         OIC_LOG(DEBUG, TAG, "Response Info :");
172         CALogPayloadInfo(info);
173     }
174     else if (CA_REQUEST_DATA == dataType)
175     {
176         CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
177         if (!reqInfo)
178         {
179             OIC_LOG(ERROR, TAG, "memory allocation failed");
180             OICFree(cadata);
181             CAFreeEndpoint(ep);
182             return NULL;
183         }
184
185         result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
186         if (CA_STATUS_OK != result)
187         {
188             OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
189             CAFreeEndpoint(ep);
190             CADestroyRequestInfoInternal(reqInfo);
191             OICFree(cadata);
192             return NULL;
193         }
194
195         if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
196                                 reqInfo->info.token, reqInfo->info.tokenLength))
197         {
198             OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
199             CAFreeEndpoint(ep);
200             CADestroyRequestInfoInternal(reqInfo);
201             OICFree(cadata);
202             return NULL;
203         }
204
205         cadata->requestInfo = reqInfo;
206         info = &reqInfo->info;
207         if (identity)
208         {
209             info->identity = *identity;
210         }
211         OIC_LOG(DEBUG, TAG, "Request Info :");
212         CALogPayloadInfo(info);
213    }
214     else if (CA_ERROR_DATA == dataType)
215     {
216         CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
217         if (!errorInfo)
218         {
219             OIC_LOG(ERROR, TAG, "Memory allocation failed!");
220             OICFree(cadata);
221             CAFreeEndpoint(ep);
222             return NULL;
223         }
224
225         CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
226         if (CA_STATUS_OK != result)
227         {
228             OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
229             CAFreeEndpoint(ep);
230             OICFree(errorInfo);
231             OICFree(cadata);
232             return NULL;
233         }
234
235         cadata->errorInfo = errorInfo;
236         info = &errorInfo->info;
237         if (identity)
238         {
239             info->identity = *identity;
240         }
241         OIC_LOG(DEBUG, TAG, "error Info :");
242         CALogPayloadInfo(info);
243     }
244
245     cadata->remoteEndpoint = ep;
246     cadata->dataType = dataType;
247
248     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
249     return cadata;
250 }
251
252 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
253 {
254     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
255     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
256
257     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
258     if (!ep)
259     {
260         OIC_LOG(ERROR, TAG, "clone failed");
261         return;
262     }
263
264     CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
265
266     if (!resInfo)
267     {
268         OIC_LOG(ERROR, TAG, "calloc failed");
269         CAFreeEndpoint(ep);
270         return;
271     }
272
273     resInfo->result = CA_RETRANSMIT_TIMEOUT;
274     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
275     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
276
277     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
278                                        endpoint);
279     if (CA_STATUS_OK != res)
280     {
281         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
282         CADestroyResponseInfoInternal(resInfo);
283         CAFreeEndpoint(ep);
284         return;
285     }
286
287     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
288     if (NULL == cadata)
289     {
290         OIC_LOG(ERROR, TAG, "memory allocation failed !");
291         CAFreeEndpoint(ep);
292         CADestroyResponseInfoInternal(resInfo);
293         return;
294     }
295
296     cadata->type = SEND_TYPE_UNICAST;
297     cadata->remoteEndpoint = ep;
298     cadata->requestInfo = NULL;
299     cadata->responseInfo = resInfo;
300
301 #ifdef WITH_BWT
302     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
303     {
304         res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
305                                                 endpoint->port);
306         if (CA_STATUS_OK != res)
307         {
308             OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
309         }
310     }
311 #endif // WITH_BWT
312
313 #ifdef SINGLE_THREAD
314     CAProcessReceivedData(cadata);
315 #else
316     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
317 #endif
318 }
319
320 static void CADestroyData(void *data, uint32_t size)
321 {
322     OIC_LOG(DEBUG, TAG, "CADestroyData IN");
323     if ((size_t)size < sizeof(CAData_t))
324     {
325         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
326     }
327     CAData_t *cadata = (CAData_t *) data;
328
329     if (NULL == cadata)
330     {
331         OIC_LOG(ERROR, TAG, "cadata is NULL");
332         return;
333     }
334
335     if (NULL != cadata->remoteEndpoint)
336     {
337         CAFreeEndpoint(cadata->remoteEndpoint);
338     }
339
340     if (NULL != cadata->requestInfo)
341     {
342         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
343     }
344
345     if (NULL != cadata->responseInfo)
346     {
347         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
348     }
349
350     if (NULL != cadata->errorInfo)
351     {
352         CADestroyErrorInfoInternal(cadata->errorInfo);
353     }
354
355     OICFree(cadata);
356     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
357 }
358
359 #ifdef SINGLE_THREAD
360 static void CAProcessReceivedData(CAData_t *data)
361 {
362     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
363     if (!data)
364     {
365         OIC_LOG(ERROR, TAG, "thread data error!!");
366         return;
367     }
368
369     // parse the data and call the callbacks.
370     // #1 parse the data
371     // #2 get endpoint
372     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
373     if (!rep)
374     {
375         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
376         return;
377     }
378
379     if (data->requestInfo && g_requestHandler)
380     {
381         g_requestHandler(rep, data->requestInfo);
382     }
383     else if (data->responseInfo && g_responseHandler)
384     {
385         g_responseHandler(rep, data->responseInfo);
386     }
387     else if (data->errorInfo && g_errorHandler)
388     {
389         g_errorHandler(rep, data->errorInfo);
390     }
391
392     CADestroyData(data, sizeof(CAData_t));
393
394     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
395 }
396 #endif
397
398 #ifndef SINGLE_THREAD
399 static void CAReceiveThreadProcess(void *threadData)
400 {
401 #ifndef SINGLE_HANDLE
402     CAData_t *data = (CAData_t *) threadData;
403     CAProcessReceivedData(data);
404 #else
405     (void)threadData;
406 #endif
407 }
408 #endif // SINGLE_THREAD
409
410 static CAResult_t CAProcessMulticastData(const CAData_t *data)
411 {
412     VERIFY_NON_NULL(data, TAG, "data");
413     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
414
415     coap_pdu_t *pdu = NULL;
416     CAInfo_t *info = NULL;
417     coap_list_t *options = NULL;
418     coap_transport_type transport;
419     CAResult_t res = CA_SEND_FAILED;
420     if (NULL != data->requestInfo)
421     {
422         OIC_LOG(DEBUG, TAG, "requestInfo is available..");
423
424         info = &data->requestInfo->info;
425         pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
426
427         if (NULL != pdu)
428         {
429 #ifdef WITH_BWT
430             if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
431             {
432                 // Blockwise transfer
433                 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
434                 if (CA_STATUS_OK != res)
435                 {
436                     OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
437                     goto exit;
438                 }
439             }
440 #endif // WITH_BWT
441         }
442         else
443         {
444             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
445             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
446             return res;
447         }
448     }
449     else if (NULL != data->responseInfo)
450     {
451         OIC_LOG(DEBUG, TAG, "responseInfo is available..");
452
453         info = &data->responseInfo->info;
454         pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
455                             &options, &transport);
456
457         if (NULL != pdu)
458         {
459 #ifdef WITH_BWT
460             if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
461             {
462                 // Blockwise transfer
463                 if (NULL != info)
464                 {
465                     res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
466                     if (CA_STATUS_OK != res)
467                     {
468                         OIC_LOG(INFO, TAG, "to write block option has failed");
469                         goto exit;
470                     }
471                 }
472             }
473 #endif // WITH_BWT
474         }
475         else
476         {
477             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
478             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
479             return res;
480         }
481     }
482     else
483     {
484         OIC_LOG(ERROR, TAG, "request or response info is empty");
485         return res;
486     }
487
488     CALogPDUInfo(pdu, data->remoteEndpoint);
489
490     OIC_LOG(DEBUG, TAG, "pdu to send :");
491     OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->hdr, pdu->length);
492
493     res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
494     if (CA_STATUS_OK != res)
495     {
496         OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
497         goto exit;
498     }
499
500     coap_delete_list(options);
501     coap_delete_pdu(pdu);
502     return res;
503
504 exit:
505     CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
506     coap_delete_list(options);
507     coap_delete_pdu(pdu);
508     return res;
509 }
510
511 static CAResult_t CAProcessSendData(const CAData_t *data)
512 {
513     VERIFY_NON_NULL(data, TAG, "data");
514     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
515
516     CAResult_t res = CA_STATUS_FAILED;
517
518     CASendDataType_t type = data->type;
519
520     coap_pdu_t *pdu = NULL;
521     CAInfo_t *info = NULL;
522     coap_list_t *options = NULL;
523     coap_transport_type transport;
524
525     if (SEND_TYPE_UNICAST == type)
526     {
527         OIC_LOG(DEBUG,TAG,"Unicast message");
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 }