Fix to resolve discovery issue when built with "scons"
[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     CAResult_t res = CA_STATUS_FAILED;
403
404     coap_pdu_t *pdu = NULL;
405     CAInfo_t *info = NULL;
406     coap_list_t *options = NULL;
407     coap_transport_type transport;
408     if (NULL != data->requestInfo)
409     {
410         OIC_LOG(DEBUG, TAG, "requestInfo is available..");
411
412         info = &data->requestInfo->info;
413         pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
414
415         if (NULL != pdu)
416         {
417 #ifdef WITH_BWT
418             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
419 #ifdef WITH_TCP
420                     && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
421 #endif
422                     )
423             {
424                 // Blockwise transfer
425                 CAResult_t res = CAAddBlockOption(&pdu, info,
426                                                   data->remoteEndpoint,
427                                                   &options);
428                 if (CA_STATUS_OK != res)
429                 {
430                     OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
431                     CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
432                     coap_delete_list(options);
433                     coap_delete_pdu(pdu);
434                     return res;
435                 }
436             }
437 #endif // WITH_BWT
438         }
439         else
440         {
441             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
442             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
443             return CA_SEND_FAILED;
444         }
445     }
446     else if (NULL != data->responseInfo)
447     {
448         OIC_LOG(DEBUG, TAG, "responseInfo is available..");
449
450         info = &data->responseInfo->info;
451         pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
452                             &options, &transport);
453
454         if (NULL != pdu)
455         {
456 #ifdef WITH_BWT
457             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
458 #ifdef WITH_TCP
459                     && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
460 #endif
461                     )
462             {
463                 // Blockwise transfer
464                 if (NULL != info)
465                 {
466                     CAResult_t res = CAAddBlockOption(&pdu, info,
467                                                       data->remoteEndpoint,
468                                                       &options);
469                     if (CA_STATUS_OK != res)
470                     {
471                         OIC_LOG(INFO, TAG, "to write block option has failed");
472                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
473                         coap_delete_list(options);
474                         coap_delete_pdu(pdu);
475                         return res;
476                     }
477                 }
478             }
479 #endif // WITH_BWT
480         }
481         else
482         {
483             OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
484             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
485             return CA_SEND_FAILED;
486         }
487     }
488     else
489     {
490         OIC_LOG(ERROR, TAG, "request or response info is empty");
491         return CA_SEND_FAILED;
492     }
493
494     CALogPDUInfo(pdu, data->remoteEndpoint);
495
496     OIC_LOG(DEBUG, TAG, "pdu to send :");
497     OIC_LOG_BUFFER(DEBUG, TAG,  (uint8_t*)pdu->hdr, pdu->length);
498
499     res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
500     if (CA_STATUS_OK != res)
501     {
502         OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
503         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
504         coap_delete_list(options);
505         coap_delete_pdu(pdu);
506         return res;
507     }
508
509     coap_delete_list(options);
510     coap_delete_pdu(pdu);
511     return CA_STATUS_OK;
512 }
513
514 static CAResult_t CAProcessSendData(const CAData_t *data)
515 {
516     VERIFY_NON_NULL(data, TAG, "data");
517     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
518
519     CAResult_t res = CA_STATUS_FAILED;
520
521     CASendDataType_t type = data->type;
522
523     coap_pdu_t *pdu = NULL;
524     CAInfo_t *info = NULL;
525     coap_list_t *options = NULL;
526     coap_transport_type transport;
527
528     if (SEND_TYPE_UNICAST == type)
529     {
530         OIC_LOG(DEBUG,TAG,"Unicast message");
531 #ifdef ROUTING_GATEWAY
532         /*
533          * When forwarding a packet, do not attempt retransmission as its the responsibility of
534          * packet originator node
535          */
536         bool skipRetransmission = false;
537 #endif
538
539         if (NULL != data->requestInfo)
540         {
541             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
542
543             info = &data->requestInfo->info;
544 #ifdef ROUTING_GATEWAY
545             skipRetransmission = data->requestInfo->info.skipRetransmission;
546 #endif
547             pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
548                                 &options, &transport);
549         }
550         else if (NULL != data->responseInfo)
551         {
552             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
553
554             info = &data->responseInfo->info;
555 #ifdef ROUTING_GATEWAY
556             skipRetransmission = data->responseInfo->info.skipRetransmission;
557 #endif
558             pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
559                                 &options, &transport);
560         }
561         else
562         {
563             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
564             return CA_STATUS_INVALID_PARAM;
565         }
566
567         // interface controller function call.
568         if (NULL != pdu)
569         {
570 #ifdef WITH_BWT
571             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
572 #ifdef WITH_TCP
573                     && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
574 #endif
575                     )
576             {
577                 // Blockwise transfer
578                 if (NULL != info)
579                 {
580                     CAResult_t res = CAAddBlockOption(&pdu, info,
581                                                       data->remoteEndpoint,
582                                                       &options);
583                     if (CA_STATUS_OK != res)
584                     {
585                         OIC_LOG(INFO, TAG, "to write block option has failed");
586                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
587                         coap_delete_list(options);
588                         coap_delete_pdu(pdu);
589                         return res;
590                     }
591                 }
592             }
593 #endif // WITH_BWT
594             CALogPDUInfo(pdu, data->remoteEndpoint);
595
596             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
597             if (CA_STATUS_OK != res)
598             {
599                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
600                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
601                 coap_delete_list(options);
602                 coap_delete_pdu(pdu);
603                 return res;
604             }
605
606 #ifdef WITH_TCP
607             if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
608             {
609                 OIC_LOG(INFO, TAG, "retransmission will be not worked");
610             }
611             else
612 #endif
613 #ifdef ROUTING_GATEWAY
614             if(!skipRetransmission)
615 #endif
616             {
617                 // for retransmission
618                 res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint,
619                                                pdu->hdr, pdu->length);
620                 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
621                 {
622                     //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
623                     OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
624                     coap_delete_list(options);
625                     coap_delete_pdu(pdu);
626                     return res;
627                 }
628             }
629
630             coap_delete_list(options);
631             coap_delete_pdu(pdu);
632         }
633         else
634         {
635             OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
636             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
637             return CA_SEND_FAILED;
638         }
639     }
640     else if (SEND_TYPE_MULTICAST == type)
641     {
642         OIC_LOG(DEBUG,TAG,"Multicast message");
643 #ifdef WITH_TCP
644         /*
645          * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
646          * That's why we need to generate two pdu's, one for IP and second for other transports.
647          * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
648          * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
649          */
650         if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
651                 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
652                     CA_ADAPTER_IP != data->remoteEndpoint->adapter))
653         {
654             data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
655             CAProcessMulticastData(data);
656             data->remoteEndpoint->adapter = CA_ADAPTER_IP;
657             CAProcessMulticastData(data);
658         }
659         else
660         {
661             CAProcessMulticastData(data);
662         }
663 #else
664         CAProcessMulticastData(data);
665 #endif
666     }
667
668     return CA_STATUS_OK;
669 }
670
671 #ifndef SINGLE_THREAD
672 static void CASendThreadProcess(void *threadData)
673 {
674     CAData_t *data = (CAData_t *) threadData;
675     CAProcessSendData(data);
676 }
677 #endif
678
679 /*
680  * If a second message arrives with the same message ID, token and the other address
681  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
682  */
683 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
684                                 CAToken_t token, uint8_t tokenLength)
685 {
686     if (!ep)
687     {
688         return true;
689     }
690     if (ep->adapter != CA_ADAPTER_IP)
691     {
692         return false;
693     }
694     if (!caglobals.ip.dualstack)
695     {
696         return false;
697     }
698
699     if (tokenLength > CA_MAX_TOKEN_LEN)
700     {
701         /*
702          * If token length is more than CA_MAX_TOKEN_LEN,
703          * we compare the first CA_MAX_TOKEN_LEN bytes only.
704          */
705         tokenLength = CA_MAX_TOKEN_LEN;
706     }
707
708     bool ret = false;
709     CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
710
711     for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
712     {
713         CAHistoryItem_t *item = &(history->items[i]);
714         if (id == item->messageId && tokenLength == item->tokenLength
715             && memcmp(item->token, token, tokenLength) == 0)
716         {
717             if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
718             {
719                 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
720                           familyFlags & CA_IPV6 ? '6' : '4');
721                 ret = true;
722                 break;
723             }
724         }
725     }
726
727     history->items[history->nextIndex].flags = familyFlags;
728     history->items[history->nextIndex].messageId = id;
729     if (token && tokenLength)
730     {
731         memcpy(history->items[history->nextIndex].token, token, tokenLength);
732         history->items[history->nextIndex].tokenLength = tokenLength;
733     }
734
735     if (++history->nextIndex >= HISTORYSIZE)
736     {
737         history->nextIndex = 0;
738     }
739
740     return ret;
741 }
742
743 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
744                                      const void *data, uint32_t dataLen)
745 {
746     VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
747     VERIFY_NON_NULL_VOID(data, TAG, "data");
748
749     OIC_LOG(DEBUG, TAG, "received pdu data :");
750     OIC_LOG_BUFFER(DEBUG, TAG,  data, dataLen);
751
752     uint32_t code = CA_NOT_FOUND;
753     CAData_t *cadata = NULL;
754
755     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
756                                                 &(sep->endpoint));
757     if (NULL == pdu)
758     {
759         OIC_LOG(ERROR, TAG, "Parse PDU failed");
760         return;
761     }
762
763     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
764     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
765     {
766         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
767         if (!cadata)
768         {
769             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
770             coap_delete_pdu(pdu);
771             return;
772         }
773     }
774     else
775     {
776         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
777         if (!cadata)
778         {
779             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
780             coap_delete_pdu(pdu);
781             return;
782         }
783
784 #ifdef WITH_TCP
785         if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
786         {
787             OIC_LOG(INFO, TAG, "retransmission is not supported");
788         }
789         else
790 #endif
791         {
792             // for retransmission
793             void *retransmissionPdu = NULL;
794             CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
795                                          pdu->length, &retransmissionPdu);
796
797 #ifndef WITH_BWT
798             // get token from saved data in retransmission list
799             if (retransmissionPdu && CA_EMPTY == code)
800             {
801                 if (cadata->responseInfo)
802                 {
803                     CAInfo_t *info = &cadata->responseInfo->info;
804                     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
805                                                        info, &(sep->endpoint));
806                     if (CA_STATUS_OK != res)
807                     {
808                         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
809                         OICFree(info->token);
810                         info->tokenLength = 0;
811                     }
812                 }
813             }
814 #endif
815             OICFree(retransmissionPdu);
816         }
817     }
818
819     cadata->type = SEND_TYPE_UNICAST;
820
821 #ifdef SINGLE_THREAD
822     CAProcessReceivedData(cadata);
823 #else
824 #ifdef WITH_BWT
825     if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
826 #ifdef WITH_TCP
827             && !CAIsSupportedCoAPOverTCP(sep->endpoint.adapter)
828 #endif
829             )
830     {
831         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
832         if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
833         {
834             OIC_LOG(ERROR, TAG, "this message does not have block option");
835             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
836         }
837         else
838         {
839             CADestroyData(cadata, sizeof(CAData_t));
840         }
841     }
842     else
843 #endif
844     {
845         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
846     }
847 #endif // SINGLE_THREAD
848
849     coap_delete_pdu(pdu);
850 }
851
852 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
853 {
854     (void)info;
855     (void)status;
856
857     if (g_nwMonitorHandler)
858     {
859         g_nwMonitorHandler(info, status);
860     }
861 }
862
863 void CAHandleRequestResponseCallbacks()
864 {
865 #ifdef SINGLE_THREAD
866     CAReadData();
867     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
868 #else
869 #ifdef SINGLE_HANDLE
870     // parse the data and call the callbacks.
871     // #1 parse the data
872     // #2 get endpoint
873
874     ca_mutex_lock(g_receiveThread.threadMutex);
875
876     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
877
878     ca_mutex_unlock(g_receiveThread.threadMutex);
879
880     if (NULL == item || NULL == item->msg)
881     {
882         return;
883     }
884
885     // get endpoint
886     CAData_t *td = (CAData_t *) item->msg;
887
888     if (td->requestInfo && g_requestHandler)
889     {
890         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
891         g_requestHandler(td->remoteEndpoint, td->requestInfo);
892     }
893     else if (td->responseInfo && g_responseHandler)
894     {
895         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
896         g_responseHandler(td->remoteEndpoint, td->responseInfo);
897     }
898     else if (td->errorInfo && g_errorHandler)
899     {
900         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
901         g_errorHandler(td->remoteEndpoint, td->errorInfo);
902     }
903
904     CADestroyData(item->msg, sizeof(CAData_t));
905     OICFree(item);
906
907 #endif // SINGLE_HANDLE
908 #endif // SINGLE_THREAD
909 }
910
911 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
912                                    CADataType_t dataType)
913 {
914     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
915
916     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
917     if (!cadata)
918     {
919         OIC_LOG(ERROR, TAG, "memory allocation failed");
920         return NULL;
921     }
922
923     if(CA_REQUEST_DATA == dataType)
924     {
925         // clone request info
926         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
927
928         if(!request)
929         {
930             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
931             OICFree(cadata);
932             return NULL;
933         }
934
935         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
936         cadata->requestInfo =  request;
937     }
938     else if(CA_RESPONSE_DATA == dataType)
939     {
940         // clone response info
941         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
942
943         if(!response)
944         {
945             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
946             OICFree(cadata);
947             return NULL;
948         }
949
950         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
951         cadata->responseInfo = response;
952     }
953     else
954     {
955         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
956         OICFree(cadata);
957         return NULL;
958     }
959
960     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
961     if (!ep)
962     {
963         OIC_LOG(ERROR, TAG, "endpoint clone failed");
964         CADestroyData(cadata, sizeof(CAData_t));
965         return NULL;
966     }
967
968     cadata->remoteEndpoint = ep;
969     cadata->dataType = dataType;
970     return cadata;
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 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
1043                                       uint8_t tokenLength, const CAHeaderOption_t *options,
1044                                       uint8_t numOptions)
1045 {
1046     (void)resourceUri;
1047     (void)token;
1048     (void)tokenLength;
1049     (void)options;
1050     (void)numOptions;
1051     return CA_NOT_SUPPORTED;
1052 }
1053
1054 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1055                              CAErrorCallback errorHandler)
1056 {
1057     g_requestHandler = ReqHandler;
1058     g_responseHandler = RespHandler;
1059     g_errorHandler = errorHandler;
1060 }
1061
1062 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1063 {
1064     g_nwMonitorHandler = nwMonitorHandler;
1065 }
1066
1067 CAResult_t CAInitializeMessageHandler()
1068 {
1069     CASetPacketReceivedCallback(CAReceivedPacketCallback);
1070
1071     CASetNetworkChangeCallback(CANetworkChangedCallback);
1072     CASetErrorHandleCallback(CAErrorHandler);
1073
1074 #ifndef SINGLE_THREAD
1075     // create thread pool
1076     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1077     if (CA_STATUS_OK != res)
1078     {
1079         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1080         return res;
1081     }
1082
1083     // send thread initialize
1084     res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1085                                      CASendThreadProcess, CADestroyData);
1086     if (CA_STATUS_OK != res)
1087     {
1088         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1089         ca_thread_pool_free(g_threadPoolHandle);
1090         g_threadPoolHandle = NULL;
1091         return res;
1092     }
1093
1094     // start send thread
1095     res = CAQueueingThreadStart(&g_sendThread);
1096     if (CA_STATUS_OK != res)
1097     {
1098         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1099         ca_thread_pool_free(g_threadPoolHandle);
1100         g_threadPoolHandle = NULL;
1101         CAQueueingThreadDestroy(&g_sendThread);
1102         return res;
1103     }
1104
1105     // receive thread initialize
1106     res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1107                                      CAReceiveThreadProcess, CADestroyData);
1108     if (CA_STATUS_OK != res)
1109     {
1110         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1111         ca_thread_pool_free(g_threadPoolHandle);
1112         g_threadPoolHandle = NULL;
1113         CAQueueingThreadDestroy(&g_sendThread);
1114         return res;
1115     }
1116
1117 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1118     // start receive thread
1119     res = CAQueueingThreadStart(&g_receiveThread);
1120     if (CA_STATUS_OK != res)
1121     {
1122         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1123         ca_thread_pool_free(g_threadPoolHandle);
1124         g_threadPoolHandle = NULL;
1125         CAQueueingThreadDestroy(&g_sendThread);
1126         CAQueueingThreadDestroy(&g_receiveThread);
1127         return res;
1128     }
1129 #endif // SINGLE_HANDLE
1130
1131     // retransmission initialize
1132     res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1133                                      CASendUnicastData, CATimeoutCallback, NULL);
1134     if (CA_STATUS_OK != res)
1135     {
1136         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1137         ca_thread_pool_free(g_threadPoolHandle);
1138         g_threadPoolHandle = NULL;
1139         CAQueueingThreadDestroy(&g_sendThread);
1140         CAQueueingThreadDestroy(&g_receiveThread);
1141         return res;
1142     }
1143
1144 #ifdef WITH_BWT
1145     // block-wise transfer initialize
1146     res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1147     if (CA_STATUS_OK != res)
1148     {
1149         OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1150         ca_thread_pool_free(g_threadPoolHandle);
1151         g_threadPoolHandle = NULL;
1152         CAQueueingThreadDestroy(&g_sendThread);
1153         CAQueueingThreadDestroy(&g_receiveThread);
1154         CARetransmissionDestroy(&g_retransmissionContext);
1155         return res;
1156     }
1157 #endif
1158
1159     // start retransmission
1160     res = CARetransmissionStart(&g_retransmissionContext);
1161     if (CA_STATUS_OK != res)
1162     {
1163         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1164         ca_thread_pool_free(g_threadPoolHandle);
1165         g_threadPoolHandle = NULL;
1166         CAQueueingThreadDestroy(&g_sendThread);
1167         CAQueueingThreadDestroy(&g_receiveThread);
1168         CARetransmissionDestroy(&g_retransmissionContext);
1169         return res;
1170     }
1171
1172     // initialize interface adapters by controller
1173     CAInitializeAdapters(g_threadPoolHandle);
1174 #else
1175     // retransmission initialize
1176     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1177                                                 CATimeoutCallback, NULL);
1178     if (CA_STATUS_OK != res)
1179     {
1180         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1181         return res;
1182     }
1183
1184     CAInitializeAdapters();
1185 #endif // SINGLE_THREAD
1186
1187     return CA_STATUS_OK;
1188 }
1189
1190 void CATerminateMessageHandler()
1191 {
1192 #ifndef SINGLE_THREAD
1193     CATransportAdapter_t connType;
1194     u_arraylist_t *list = CAGetSelectedNetworkList();
1195     uint32_t length = u_arraylist_length(list);
1196
1197     uint32_t i = 0;
1198     for (i = 0; i < length; i++)
1199     {
1200         void* ptrType = u_arraylist_get(list, i);
1201
1202         if (NULL == ptrType)
1203         {
1204             continue;
1205         }
1206
1207         connType = *(CATransportAdapter_t *)ptrType;
1208         CAStopAdapter(connType);
1209     }
1210
1211     // stop retransmission
1212     if (NULL != g_retransmissionContext.threadMutex)
1213     {
1214         CARetransmissionStop(&g_retransmissionContext);
1215     }
1216
1217     // stop thread
1218     // delete thread data
1219     if (NULL != g_sendThread.threadMutex)
1220     {
1221         CAQueueingThreadStop(&g_sendThread);
1222     }
1223
1224     // stop thread
1225     // delete thread data
1226     if (NULL != g_receiveThread.threadMutex)
1227     {
1228 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1229         CAQueueingThreadStop(&g_receiveThread);
1230 #endif
1231     }
1232
1233     // destroy thread pool
1234     if (NULL != g_threadPoolHandle)
1235     {
1236         ca_thread_pool_free(g_threadPoolHandle);
1237         g_threadPoolHandle = NULL;
1238     }
1239
1240 #ifdef WITH_BWT
1241     CATerminateBlockWiseTransfer();
1242 #endif
1243     CARetransmissionDestroy(&g_retransmissionContext);
1244     CAQueueingThreadDestroy(&g_sendThread);
1245     CAQueueingThreadDestroy(&g_receiveThread);
1246
1247     // terminate interface adapters by controller
1248     CATerminateAdapters();
1249 #else
1250     // terminate interface adapters by controller
1251     CATerminateAdapters();
1252
1253     // stop retransmission
1254     CARetransmissionStop(&g_retransmissionContext);
1255     CARetransmissionDestroy(&g_retransmissionContext);
1256 #endif // SINGLE_THREAD
1257 }
1258
1259 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1260 {
1261     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1262     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1263
1264     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1265
1266 #ifdef WITH_TCP
1267     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1268     {
1269         OIC_LOG(DEBUG, TAG, "pdu header data :");
1270         OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->hdr, pdu->length);
1271     }
1272     else
1273 #endif
1274     {
1275         OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1276
1277         OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1278
1279         OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1280
1281         OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1282                        pdu->hdr->coap_hdr_udp_t.token_length);
1283     }
1284 }
1285
1286 static void CALogPayloadInfo(CAInfo_t *info)
1287 {
1288     if(info)
1289     {
1290         if (info->options)
1291         {
1292             for (uint32_t i = 0; i < info->numOptions; i++)
1293             {
1294                 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1295
1296                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1297             }
1298         }
1299
1300         if (info->payload)
1301         {
1302             OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1303                       info->payloadSize);
1304         }
1305
1306         if (info->token)
1307         {
1308             OIC_LOG(DEBUG, TAG, "token:");
1309             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1310                            info->tokenLength);
1311         }
1312         OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1313     }
1314     else
1315     {
1316         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1317     }
1318 }
1319
1320 void CAErrorHandler(const CAEndpoint_t *endpoint,
1321                     const void *data, uint32_t dataLen,
1322                     CAResult_t result)
1323 {
1324     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1325
1326 #ifndef SINGLE_THREAD
1327     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1328     VERIFY_NON_NULL_VOID(data, TAG, "data");
1329
1330     uint32_t code = CA_NOT_FOUND;
1331     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1332     //Get PDU data
1333     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1334     if (NULL == pdu)
1335     {
1336         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1337         return;
1338     }
1339
1340     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1341     if(!cadata)
1342     {
1343         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1344         coap_delete_pdu(pdu);
1345         return;
1346     }
1347
1348     cadata->errorInfo->result = result;
1349
1350     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1351     coap_delete_pdu(pdu);
1352 #endif
1353
1354     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1355     return;
1356 }
1357
1358 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1359 {
1360     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1361 #ifndef SINGLE_THREAD
1362     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1363     if (!cadata)
1364     {
1365         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1366         return;
1367     }
1368
1369     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1370     if (!ep)
1371     {
1372         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1373         OICFree(cadata);
1374         return;
1375     }
1376
1377     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1378     if (!errorInfo)
1379     {
1380         OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1381         OICFree(cadata);
1382         CAFreeEndpoint(ep);
1383         return;
1384     }
1385
1386     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1387     if (CA_STATUS_OK != res)
1388     {
1389         OIC_LOG(ERROR, TAG, "info clone failed");
1390         OICFree(cadata);
1391         OICFree(errorInfo);
1392         CAFreeEndpoint(ep);
1393         return;
1394     }
1395
1396     errorInfo->result = result;
1397     cadata->remoteEndpoint = ep;
1398     cadata->errorInfo = errorInfo;
1399     cadata->dataType = CA_ERROR_DATA;
1400
1401     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1402 #endif
1403     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1404 }