Removed unnecessary/duplicated code in connectivity abstraction
[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 SINGLE_THREAD
301     CAProcessReceivedData(cadata);
302 #else
303     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
304 #endif
305 }
306
307 static void CADestroyData(void *data, uint32_t size)
308 {
309     OIC_LOG(DEBUG, TAG, "CADestroyData IN");
310     if ((size_t)size < sizeof(CAData_t))
311     {
312         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
313     }
314     CAData_t *cadata = (CAData_t *) data;
315
316     if (NULL == cadata)
317     {
318         OIC_LOG(ERROR, TAG, "cadata is NULL");
319         return;
320     }
321
322     if (NULL != cadata->remoteEndpoint)
323     {
324         CAFreeEndpoint(cadata->remoteEndpoint);
325     }
326
327     if (NULL != cadata->requestInfo)
328     {
329         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
330     }
331
332     if (NULL != cadata->responseInfo)
333     {
334         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
335     }
336
337     if (NULL != cadata->errorInfo)
338     {
339         CADestroyErrorInfoInternal(cadata->errorInfo);
340     }
341
342     OICFree(cadata);
343     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
344 }
345
346 #ifdef SINGLE_THREAD
347 static void CAProcessReceivedData(CAData_t *data)
348 {
349     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
350     if (!data)
351     {
352         OIC_LOG(ERROR, TAG, "thread data error!!");
353         return;
354     }
355
356     // parse the data and call the callbacks.
357     // #1 parse the data
358     // #2 get endpoint
359     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
360     if (!rep)
361     {
362         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
363         return;
364     }
365
366     if (data->requestInfo && g_requestHandler)
367     {
368         g_requestHandler(rep, data->requestInfo);
369     }
370     else if (data->responseInfo && g_responseHandler)
371     {
372         g_responseHandler(rep, data->responseInfo);
373     }
374     else if (data->errorInfo && g_errorHandler)
375     {
376         g_errorHandler(rep, data->errorInfo);
377     }
378
379     CADestroyData(data, sizeof(CAData_t));
380
381     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
382 }
383 #endif
384
385 #ifndef SINGLE_THREAD
386 static void CAReceiveThreadProcess(void *threadData)
387 {
388 #ifndef SINGLE_HANDLE
389     CAData_t *data = (CAData_t *) threadData;
390     CAProcessReceivedData(data);
391 #else
392     (void)threadData;
393 #endif
394 }
395 #endif // SINGLE_THREAD
396
397 static CAResult_t CAProcessMulticastData(const CAData_t *data)
398 {
399     VERIFY_NON_NULL(data, TAG, "data");
400     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
401
402     coap_pdu_t *pdu = NULL;
403     CAInfo_t *info = NULL;
404     coap_list_t *options = NULL;
405     coap_transport_type transport;
406     CAResult_t res = CA_SEND_FAILED;
407     if (NULL != data->requestInfo)
408     {
409         OIC_LOG(DEBUG, TAG, "requestInfo is available..");
410
411         info = &data->requestInfo->info;
412         pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
413
414         if (NULL != pdu)
415         {
416 #ifdef WITH_BWT
417             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
418 #ifdef WITH_TCP
419                     && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
420 #endif
421                     )
422             {
423                 // Blockwise transfer
424                 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
425                 if (CA_STATUS_OK != res)
426                 {
427                     OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
428                     goto exit;
429                 }
430             }
431 #endif // WITH_BWT
432         }
433         else
434         {
435             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
436             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
437             return res;
438         }
439     }
440     else if (NULL != data->responseInfo)
441     {
442         OIC_LOG(DEBUG, TAG, "responseInfo is available..");
443
444         info = &data->responseInfo->info;
445         pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
446                             &options, &transport);
447
448         if (NULL != pdu)
449         {
450 #ifdef WITH_BWT
451             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
452 #ifdef WITH_TCP
453                     && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
454 #endif
455                     )
456             {
457                 // Blockwise transfer
458                 if (NULL != info)
459                 {
460                     res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
461                     if (CA_STATUS_OK != res)
462                     {
463                         OIC_LOG(INFO, TAG, "to write block option has failed");
464                         goto exit;
465                     }
466                 }
467             }
468 #endif // WITH_BWT
469         }
470         else
471         {
472             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
473             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
474             return res;
475         }
476     }
477     else
478     {
479         OIC_LOG(ERROR, TAG, "request or response info is empty");
480         return res;
481     }
482
483     CALogPDUInfo(pdu, data->remoteEndpoint);
484
485     OIC_LOG(DEBUG, TAG, "pdu to send :");
486     OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->hdr, pdu->length);
487
488     res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
489     if (CA_STATUS_OK != res)
490     {
491         OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
492         goto exit;
493     }
494
495     coap_delete_list(options);
496     coap_delete_pdu(pdu);
497     return res;
498
499 exit:
500     CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
501     coap_delete_list(options);
502     coap_delete_pdu(pdu);
503     return res;
504 }
505
506 static CAResult_t CAProcessSendData(const CAData_t *data)
507 {
508     VERIFY_NON_NULL(data, TAG, "data");
509     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
510
511     CAResult_t res = CA_STATUS_FAILED;
512
513     CASendDataType_t type = data->type;
514
515     coap_pdu_t *pdu = NULL;
516     CAInfo_t *info = NULL;
517     coap_list_t *options = NULL;
518     coap_transport_type transport;
519
520     if (SEND_TYPE_UNICAST == type)
521     {
522         OIC_LOG(DEBUG,TAG,"Unicast message");
523 #ifdef ROUTING_GATEWAY
524         /*
525          * When forwarding a packet, do not attempt retransmission as its the responsibility of
526          * packet originator node
527          */
528         bool skipRetransmission = false;
529 #endif
530
531         if (NULL != data->requestInfo)
532         {
533             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
534
535             info = &data->requestInfo->info;
536 #ifdef ROUTING_GATEWAY
537             skipRetransmission = data->requestInfo->info.skipRetransmission;
538 #endif
539             pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
540                                 &options, &transport);
541         }
542         else if (NULL != data->responseInfo)
543         {
544             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
545
546             info = &data->responseInfo->info;
547 #ifdef ROUTING_GATEWAY
548             skipRetransmission = data->responseInfo->info.skipRetransmission;
549 #endif
550             pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
551                                 &options, &transport);
552         }
553         else
554         {
555             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
556             return CA_STATUS_INVALID_PARAM;
557         }
558
559         // interface controller function call.
560         if (NULL != pdu)
561         {
562 #ifdef WITH_BWT
563             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
564 #ifdef WITH_TCP
565                     && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
566 #endif
567                     )
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 #ifndef WITH_BWT
797             // get token from saved data in retransmission list
798             if (retransmissionPdu && CA_EMPTY == code)
799             {
800                 if (cadata->responseInfo)
801                 {
802                     CAInfo_t *info = &cadata->responseInfo->info;
803                     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
804                                                        info, &(sep->endpoint));
805                     if (CA_STATUS_OK != res)
806                     {
807                         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
808                         OICFree(info->token);
809                         info->tokenLength = 0;
810                     }
811                 }
812             }
813 #endif
814             OICFree(retransmissionPdu);
815         }
816     }
817
818     cadata->type = SEND_TYPE_UNICAST;
819
820 #ifdef SINGLE_THREAD
821     CAProcessReceivedData(cadata);
822 #else
823 #ifdef WITH_BWT
824     if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
825 #ifdef WITH_TCP
826             && !CAIsSupportedCoAPOverTCP(sep->endpoint.adapter)
827 #endif
828             )
829     {
830         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
831         if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
832         {
833             OIC_LOG(ERROR, TAG, "this message does not have block option");
834             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
835         }
836         else
837         {
838             CADestroyData(cadata, sizeof(CAData_t));
839         }
840     }
841     else
842 #endif
843     {
844         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
845     }
846 #endif // SINGLE_THREAD
847
848     coap_delete_pdu(pdu);
849 }
850
851 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
852 {
853     (void)info;
854     (void)status;
855
856     if (g_nwMonitorHandler)
857     {
858         g_nwMonitorHandler(info, status);
859     }
860 }
861
862 void CAHandleRequestResponseCallbacks()
863 {
864 #ifdef SINGLE_THREAD
865     CAReadData();
866     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
867 #else
868 #ifdef SINGLE_HANDLE
869     // parse the data and call the callbacks.
870     // #1 parse the data
871     // #2 get endpoint
872
873     ca_mutex_lock(g_receiveThread.threadMutex);
874
875     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
876
877     ca_mutex_unlock(g_receiveThread.threadMutex);
878
879     if (NULL == item || NULL == item->msg)
880     {
881         return;
882     }
883
884     // get endpoint
885     CAData_t *td = (CAData_t *) item->msg;
886
887     if (td->requestInfo && g_requestHandler)
888     {
889         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
890         g_requestHandler(td->remoteEndpoint, td->requestInfo);
891     }
892     else if (td->responseInfo && g_responseHandler)
893     {
894         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
895         g_responseHandler(td->remoteEndpoint, td->responseInfo);
896     }
897     else if (td->errorInfo && g_errorHandler)
898     {
899         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
900         g_errorHandler(td->remoteEndpoint, td->errorInfo);
901     }
902
903     CADestroyData(item->msg, sizeof(CAData_t));
904     OICFree(item);
905
906 #endif // SINGLE_HANDLE
907 #endif // SINGLE_THREAD
908 }
909
910 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
911                                    CADataType_t dataType)
912 {
913     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
914
915     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
916     if (!cadata)
917     {
918         OIC_LOG(ERROR, TAG, "memory allocation failed");
919         return NULL;
920     }
921
922     if(CA_REQUEST_DATA == dataType)
923     {
924         // clone request info
925         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
926
927         if(!request)
928         {
929             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
930             goto exit;
931         }
932
933         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
934         cadata->requestInfo =  request;
935     }
936     else if(CA_RESPONSE_DATA == dataType)
937     {
938         // clone response info
939         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
940
941         if(!response)
942         {
943             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
944             goto exit;
945         }
946
947         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
948         cadata->responseInfo = response;
949     }
950     else
951     {
952         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
953         goto exit;
954     }
955
956     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
957     if (!ep)
958     {
959         OIC_LOG(ERROR, TAG, "endpoint clone failed");
960         CADestroyData(cadata, sizeof(CAData_t));
961         return NULL;
962     }
963
964     cadata->remoteEndpoint = ep;
965     cadata->dataType = dataType;
966     return cadata;
967
968 exit:
969     OICFree(cadata);
970     return NULL;
971 }
972
973 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
974                                CADataType_t dataType)
975 {
976     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
977     VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
978
979     if (false == CAIsSelectedNetworkAvailable())
980     {
981         return CA_STATUS_FAILED;
982     }
983
984 #ifdef ARDUINO
985     // If max retransmission queue is reached, then don't handle new request
986     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
987     {
988         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
989         return CA_SEND_FAILED;
990     }
991 #endif // ARDUINO
992
993     CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
994     if(!data)
995     {
996         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
997         return CA_MEMORY_ALLOC_FAILED;
998     }
999
1000 #ifdef SINGLE_THREAD
1001     CAResult_t result = CAProcessSendData(data);
1002     if(CA_STATUS_OK != result)
1003     {
1004         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1005         CADestroyData(data, sizeof(CAData_t));
1006         return result;
1007     }
1008
1009     CADestroyData(data, sizeof(CAData_t));
1010 #else
1011 #ifdef WITH_BWT
1012     if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
1013 #ifdef WITH_TCP
1014             && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
1015 #endif
1016             )
1017     {
1018         // send block data
1019         CAResult_t res = CASendBlockWiseData(data);
1020         if(CA_NOT_SUPPORTED == res)
1021         {
1022             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1023             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1024             return CA_STATUS_OK;
1025         }
1026         else
1027         {
1028             CADestroyData(data, sizeof(CAData_t));
1029         }
1030         return res;
1031     }
1032     else
1033 #endif // WITH_BWT
1034     {
1035         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1036     }
1037 #endif // SINGLE_THREAD
1038
1039     return CA_STATUS_OK;
1040 }
1041
1042 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1043                              CAErrorCallback errorHandler)
1044 {
1045     g_requestHandler = ReqHandler;
1046     g_responseHandler = RespHandler;
1047     g_errorHandler = errorHandler;
1048 }
1049
1050 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1051 {
1052     g_nwMonitorHandler = nwMonitorHandler;
1053 }
1054
1055 CAResult_t CAInitializeMessageHandler()
1056 {
1057     CASetPacketReceivedCallback(CAReceivedPacketCallback);
1058
1059     CASetNetworkChangeCallback(CANetworkChangedCallback);
1060     CASetErrorHandleCallback(CAErrorHandler);
1061
1062 #ifndef SINGLE_THREAD
1063     // create thread pool
1064     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1065     if (CA_STATUS_OK != res)
1066     {
1067         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1068         return res;
1069     }
1070
1071     // send thread initialize
1072     res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1073                                      CASendThreadProcess, CADestroyData);
1074     if (CA_STATUS_OK != res)
1075     {
1076         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1077         ca_thread_pool_free(g_threadPoolHandle);
1078         g_threadPoolHandle = NULL;
1079         return res;
1080     }
1081
1082     // start send thread
1083     res = CAQueueingThreadStart(&g_sendThread);
1084     if (CA_STATUS_OK != res)
1085     {
1086         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1087         ca_thread_pool_free(g_threadPoolHandle);
1088         g_threadPoolHandle = NULL;
1089         CAQueueingThreadDestroy(&g_sendThread);
1090         return res;
1091     }
1092
1093     // receive thread initialize
1094     res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1095                                      CAReceiveThreadProcess, CADestroyData);
1096     if (CA_STATUS_OK != res)
1097     {
1098         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1099         ca_thread_pool_free(g_threadPoolHandle);
1100         g_threadPoolHandle = NULL;
1101         CAQueueingThreadDestroy(&g_sendThread);
1102         return res;
1103     }
1104
1105 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1106     // start receive thread
1107     res = CAQueueingThreadStart(&g_receiveThread);
1108     if (CA_STATUS_OK != res)
1109     {
1110         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1111         ca_thread_pool_free(g_threadPoolHandle);
1112         g_threadPoolHandle = NULL;
1113         CAQueueingThreadDestroy(&g_sendThread);
1114         CAQueueingThreadDestroy(&g_receiveThread);
1115         return res;
1116     }
1117 #endif // SINGLE_HANDLE
1118
1119     // retransmission initialize
1120     res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1121                                      CASendUnicastData, CATimeoutCallback, NULL);
1122     if (CA_STATUS_OK != res)
1123     {
1124         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1125         ca_thread_pool_free(g_threadPoolHandle);
1126         g_threadPoolHandle = NULL;
1127         CAQueueingThreadDestroy(&g_sendThread);
1128         CAQueueingThreadDestroy(&g_receiveThread);
1129         return res;
1130     }
1131
1132 #ifdef WITH_BWT
1133     // block-wise transfer initialize
1134     res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1135     if (CA_STATUS_OK != res)
1136     {
1137         OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1138         ca_thread_pool_free(g_threadPoolHandle);
1139         g_threadPoolHandle = NULL;
1140         CAQueueingThreadDestroy(&g_sendThread);
1141         CAQueueingThreadDestroy(&g_receiveThread);
1142         CARetransmissionDestroy(&g_retransmissionContext);
1143         return res;
1144     }
1145 #endif
1146
1147     // start retransmission
1148     res = CARetransmissionStart(&g_retransmissionContext);
1149     if (CA_STATUS_OK != res)
1150     {
1151         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1152         ca_thread_pool_free(g_threadPoolHandle);
1153         g_threadPoolHandle = NULL;
1154         CAQueueingThreadDestroy(&g_sendThread);
1155         CAQueueingThreadDestroy(&g_receiveThread);
1156         CARetransmissionDestroy(&g_retransmissionContext);
1157         return res;
1158     }
1159
1160     // initialize interface adapters by controller
1161     CAInitializeAdapters(g_threadPoolHandle);
1162 #else
1163     // retransmission initialize
1164     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1165                                                 CATimeoutCallback, NULL);
1166     if (CA_STATUS_OK != res)
1167     {
1168         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1169         return res;
1170     }
1171
1172     CAInitializeAdapters();
1173 #endif // SINGLE_THREAD
1174
1175     return CA_STATUS_OK;
1176 }
1177
1178 void CATerminateMessageHandler()
1179 {
1180 #ifndef SINGLE_THREAD
1181     CATransportAdapter_t connType;
1182     u_arraylist_t *list = CAGetSelectedNetworkList();
1183     uint32_t length = u_arraylist_length(list);
1184
1185     uint32_t i = 0;
1186     for (i = 0; i < length; i++)
1187     {
1188         void* ptrType = u_arraylist_get(list, i);
1189
1190         if (NULL == ptrType)
1191         {
1192             continue;
1193         }
1194
1195         connType = *(CATransportAdapter_t *)ptrType;
1196         CAStopAdapter(connType);
1197     }
1198
1199     // stop retransmission
1200     if (NULL != g_retransmissionContext.threadMutex)
1201     {
1202         CARetransmissionStop(&g_retransmissionContext);
1203     }
1204
1205     // stop thread
1206     // delete thread data
1207     if (NULL != g_sendThread.threadMutex)
1208     {
1209         CAQueueingThreadStop(&g_sendThread);
1210     }
1211
1212     // stop thread
1213     // delete thread data
1214     if (NULL != g_receiveThread.threadMutex)
1215     {
1216 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1217         CAQueueingThreadStop(&g_receiveThread);
1218 #endif
1219     }
1220
1221     // destroy thread pool
1222     if (NULL != g_threadPoolHandle)
1223     {
1224         ca_thread_pool_free(g_threadPoolHandle);
1225         g_threadPoolHandle = NULL;
1226     }
1227
1228 #ifdef WITH_BWT
1229     CATerminateBlockWiseTransfer();
1230 #endif
1231     CARetransmissionDestroy(&g_retransmissionContext);
1232     CAQueueingThreadDestroy(&g_sendThread);
1233     CAQueueingThreadDestroy(&g_receiveThread);
1234
1235     // terminate interface adapters by controller
1236     CATerminateAdapters();
1237 #else
1238     // terminate interface adapters by controller
1239     CATerminateAdapters();
1240
1241     // stop retransmission
1242     CARetransmissionStop(&g_retransmissionContext);
1243     CARetransmissionDestroy(&g_retransmissionContext);
1244 #endif // SINGLE_THREAD
1245 }
1246
1247 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1248 {
1249     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1250     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1251
1252     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1253
1254 #ifdef WITH_TCP
1255     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1256     {
1257         OIC_LOG(DEBUG, TAG, "pdu header data :");
1258         OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->hdr, pdu->length);
1259     }
1260     else
1261 #endif
1262     {
1263         OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1264
1265         OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1266
1267         OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1268
1269         OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1270                        pdu->hdr->coap_hdr_udp_t.token_length);
1271     }
1272 }
1273
1274 static void CALogPayloadInfo(CAInfo_t *info)
1275 {
1276     if(info)
1277     {
1278         if (info->options)
1279         {
1280             for (uint32_t i = 0; i < info->numOptions; i++)
1281             {
1282                 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1283
1284                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1285             }
1286         }
1287
1288         if (info->payload)
1289         {
1290             OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1291                       info->payloadSize);
1292         }
1293
1294         if (info->token)
1295         {
1296             OIC_LOG(DEBUG, TAG, "token:");
1297             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1298                            info->tokenLength);
1299         }
1300         OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1301     }
1302     else
1303     {
1304         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1305     }
1306 }
1307
1308 void CAErrorHandler(const CAEndpoint_t *endpoint,
1309                     const void *data, uint32_t dataLen,
1310                     CAResult_t result)
1311 {
1312     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1313
1314 #ifndef SINGLE_THREAD
1315     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1316     VERIFY_NON_NULL_VOID(data, TAG, "data");
1317
1318     uint32_t code = CA_NOT_FOUND;
1319     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1320     //Get PDU data
1321     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1322     if (NULL == pdu)
1323     {
1324         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1325         return;
1326     }
1327
1328     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1329     if(!cadata)
1330     {
1331         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1332         coap_delete_pdu(pdu);
1333         return;
1334     }
1335
1336     cadata->errorInfo->result = result;
1337
1338     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1339     coap_delete_pdu(pdu);
1340 #endif
1341
1342     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1343     return;
1344 }
1345
1346 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1347 {
1348     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1349 #ifndef SINGLE_THREAD
1350     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1351     if (!cadata)
1352     {
1353         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1354         return;
1355     }
1356
1357     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1358     if (!ep)
1359     {
1360         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1361         OICFree(cadata);
1362         return;
1363     }
1364
1365     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1366     if (!errorInfo)
1367     {
1368         OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1369         OICFree(cadata);
1370         CAFreeEndpoint(ep);
1371         return;
1372     }
1373
1374     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1375     if (CA_STATUS_OK != res)
1376     {
1377         OIC_LOG(ERROR, TAG, "info clone failed");
1378         OICFree(cadata);
1379         OICFree(errorInfo);
1380         CAFreeEndpoint(ep);
1381         return;
1382     }
1383
1384     errorInfo->result = result;
1385     cadata->remoteEndpoint = ep;
1386     cadata->errorInfo = errorInfo;
1387     cadata->dataType = CA_ERROR_DATA;
1388
1389     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1390 #endif
1391     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1392 }