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