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