Merge branch 'master' into cloud-interface
[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             if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
655             {
656                 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
657             }
658             else
659             {
660                 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
661             }
662             CAProcessMulticastData(data);
663             data->remoteEndpoint->adapter = CA_ADAPTER_IP;
664             CAProcessMulticastData(data);
665         }
666         else
667         {
668             CAProcessMulticastData(data);
669         }
670 #else
671         CAProcessMulticastData(data);
672 #endif
673     }
674
675     return CA_STATUS_OK;
676 }
677
678 #ifndef SINGLE_THREAD
679 static void CASendThreadProcess(void *threadData)
680 {
681     CAData_t *data = (CAData_t *) threadData;
682     CAProcessSendData(data);
683 }
684 #endif
685
686 /*
687  * If a second message arrives with the same message ID, token and the other address
688  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
689  */
690 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
691                                 CAToken_t token, uint8_t tokenLength)
692 {
693     if (!ep)
694     {
695         return true;
696     }
697     if (ep->adapter != CA_ADAPTER_IP)
698     {
699         return false;
700     }
701     if (!caglobals.ip.dualstack)
702     {
703         return false;
704     }
705
706     if (tokenLength > CA_MAX_TOKEN_LEN)
707     {
708         /*
709          * If token length is more than CA_MAX_TOKEN_LEN,
710          * we compare the first CA_MAX_TOKEN_LEN bytes only.
711          */
712         tokenLength = CA_MAX_TOKEN_LEN;
713     }
714
715     bool ret = false;
716     CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
717
718     for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
719     {
720         CAHistoryItem_t *item = &(history->items[i]);
721         if (id == item->messageId && tokenLength == item->tokenLength
722             && memcmp(item->token, token, tokenLength) == 0)
723         {
724             if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
725             {
726                 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
727                           familyFlags & CA_IPV6 ? '6' : '4');
728                 ret = true;
729                 break;
730             }
731         }
732     }
733
734     history->items[history->nextIndex].flags = familyFlags;
735     history->items[history->nextIndex].messageId = id;
736     if (token && tokenLength)
737     {
738         memcpy(history->items[history->nextIndex].token, token, tokenLength);
739         history->items[history->nextIndex].tokenLength = tokenLength;
740     }
741
742     if (++history->nextIndex >= HISTORYSIZE)
743     {
744         history->nextIndex = 0;
745     }
746
747     return ret;
748 }
749
750 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
751                                      const void *data, uint32_t dataLen)
752 {
753     VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
754     VERIFY_NON_NULL_VOID(data, TAG, "data");
755
756     OIC_LOG(DEBUG, TAG, "received pdu data :");
757     OIC_LOG_BUFFER(DEBUG, TAG,  data, dataLen);
758
759     uint32_t code = CA_NOT_FOUND;
760     CAData_t *cadata = NULL;
761
762     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
763                                                 &(sep->endpoint));
764     if (NULL == pdu)
765     {
766         OIC_LOG(ERROR, TAG, "Parse PDU failed");
767         return;
768     }
769
770     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
771     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
772     {
773         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
774         if (!cadata)
775         {
776             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
777             coap_delete_pdu(pdu);
778             return;
779         }
780     }
781     else
782     {
783         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
784         if (!cadata)
785         {
786             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
787             coap_delete_pdu(pdu);
788             return;
789         }
790
791 #ifdef WITH_TCP
792         if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
793         {
794             OIC_LOG(INFO, TAG, "retransmission is not supported");
795         }
796         else
797 #endif
798         {
799             // for retransmission
800             void *retransmissionPdu = NULL;
801             CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
802                                          pdu->length, &retransmissionPdu);
803
804 #ifndef WITH_BWT
805             // get token from saved data in retransmission list
806             if (retransmissionPdu && CA_EMPTY == code)
807             {
808                 if (cadata->responseInfo)
809                 {
810                     CAInfo_t *info = &cadata->responseInfo->info;
811                     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
812                                                        info, &(sep->endpoint));
813                     if (CA_STATUS_OK != res)
814                     {
815                         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
816                         OICFree(info->token);
817                         info->tokenLength = 0;
818                     }
819                 }
820             }
821 #endif
822             OICFree(retransmissionPdu);
823         }
824     }
825
826     cadata->type = SEND_TYPE_UNICAST;
827
828 #ifdef SINGLE_THREAD
829     CAProcessReceivedData(cadata);
830 #else
831 #ifdef WITH_BWT
832     if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
833 #ifdef WITH_TCP
834             && !CAIsSupportedCoAPOverTCP(sep->endpoint.adapter)
835 #endif
836             )
837     {
838         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
839         if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
840         {
841             OIC_LOG(ERROR, TAG, "this message does not have block option");
842             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
843         }
844         else
845         {
846             CADestroyData(cadata, sizeof(CAData_t));
847         }
848     }
849     else
850 #endif
851     {
852         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
853     }
854 #endif // SINGLE_THREAD
855
856     coap_delete_pdu(pdu);
857 }
858
859 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
860 {
861     (void)info;
862     (void)status;
863
864     if (g_nwMonitorHandler)
865     {
866         g_nwMonitorHandler(info, status);
867     }
868 }
869
870 void CAHandleRequestResponseCallbacks()
871 {
872 #ifdef SINGLE_THREAD
873     CAReadData();
874     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
875 #else
876 #ifdef SINGLE_HANDLE
877     // parse the data and call the callbacks.
878     // #1 parse the data
879     // #2 get endpoint
880
881     ca_mutex_lock(g_receiveThread.threadMutex);
882
883     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
884
885     ca_mutex_unlock(g_receiveThread.threadMutex);
886
887     if (NULL == item || NULL == item->msg)
888     {
889         return;
890     }
891
892     // get endpoint
893     CAData_t *td = (CAData_t *) item->msg;
894
895     if (td->requestInfo && g_requestHandler)
896     {
897         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
898         g_requestHandler(td->remoteEndpoint, td->requestInfo);
899     }
900     else if (td->responseInfo && g_responseHandler)
901     {
902         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
903         g_responseHandler(td->remoteEndpoint, td->responseInfo);
904     }
905     else if (td->errorInfo && g_errorHandler)
906     {
907         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
908         g_errorHandler(td->remoteEndpoint, td->errorInfo);
909     }
910
911     CADestroyData(item->msg, sizeof(CAData_t));
912     OICFree(item);
913
914 #endif // SINGLE_HANDLE
915 #endif // SINGLE_THREAD
916 }
917
918 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
919                                    CADataType_t dataType)
920 {
921     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
922
923     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
924     if (!cadata)
925     {
926         OIC_LOG(ERROR, TAG, "memory allocation failed");
927         return NULL;
928     }
929
930     if(CA_REQUEST_DATA == dataType)
931     {
932         // clone request info
933         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
934
935         if(!request)
936         {
937             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
938             OICFree(cadata);
939             return NULL;
940         }
941
942         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
943         cadata->requestInfo =  request;
944     }
945     else if(CA_RESPONSE_DATA == dataType)
946     {
947         // clone response info
948         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
949
950         if(!response)
951         {
952             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
953             OICFree(cadata);
954             return NULL;
955         }
956
957         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
958         cadata->responseInfo = response;
959     }
960     else
961     {
962         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
963         OICFree(cadata);
964         return NULL;
965     }
966
967     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
968     if (!ep)
969     {
970         OIC_LOG(ERROR, TAG, "endpoint clone failed");
971         CADestroyData(cadata, sizeof(CAData_t));
972         return NULL;
973     }
974
975     cadata->remoteEndpoint = ep;
976     cadata->dataType = dataType;
977     return cadata;
978 }
979
980 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
981                                CADataType_t dataType)
982 {
983     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
984     VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
985
986     if (false == CAIsSelectedNetworkAvailable())
987     {
988         return CA_STATUS_FAILED;
989     }
990
991 #ifdef ARDUINO
992     // If max retransmission queue is reached, then don't handle new request
993     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
994     {
995         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
996         return CA_SEND_FAILED;
997     }
998 #endif // ARDUINO
999
1000     CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
1001     if(!data)
1002     {
1003         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
1004         return CA_MEMORY_ALLOC_FAILED;
1005     }
1006
1007 #ifdef SINGLE_THREAD
1008     CAResult_t result = CAProcessSendData(data);
1009     if(CA_STATUS_OK != result)
1010     {
1011         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1012         CADestroyData(data, sizeof(CAData_t));
1013         return result;
1014     }
1015
1016     CADestroyData(data, sizeof(CAData_t));
1017 #else
1018 #ifdef WITH_BWT
1019     if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
1020 #ifdef WITH_TCP
1021             && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
1022 #endif
1023             )
1024     {
1025         // send block data
1026         CAResult_t res = CASendBlockWiseData(data);
1027         if(CA_NOT_SUPPORTED == res)
1028         {
1029             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1030             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1031             return CA_STATUS_OK;
1032         }
1033         else
1034         {
1035             CADestroyData(data, sizeof(CAData_t));
1036         }
1037         return res;
1038     }
1039     else
1040 #endif // WITH_BWT
1041     {
1042         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1043     }
1044 #endif // SINGLE_THREAD
1045
1046     return CA_STATUS_OK;
1047 }
1048
1049 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
1050                                       uint8_t tokenLength, const CAHeaderOption_t *options,
1051                                       uint8_t numOptions)
1052 {
1053     (void)resourceUri;
1054     (void)token;
1055     (void)tokenLength;
1056     (void)options;
1057     (void)numOptions;
1058     return CA_NOT_SUPPORTED;
1059 }
1060
1061 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1062                              CAErrorCallback errorHandler)
1063 {
1064     g_requestHandler = ReqHandler;
1065     g_responseHandler = RespHandler;
1066     g_errorHandler = errorHandler;
1067 }
1068
1069 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1070 {
1071     g_nwMonitorHandler = nwMonitorHandler;
1072 }
1073
1074 CAResult_t CAInitializeMessageHandler()
1075 {
1076     CASetPacketReceivedCallback(CAReceivedPacketCallback);
1077
1078     CASetNetworkChangeCallback(CANetworkChangedCallback);
1079     CASetErrorHandleCallback(CAErrorHandler);
1080
1081 #ifndef SINGLE_THREAD
1082     // create thread pool
1083     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1084     if (CA_STATUS_OK != res)
1085     {
1086         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1087         return res;
1088     }
1089
1090     // send thread initialize
1091     res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1092                                      CASendThreadProcess, CADestroyData);
1093     if (CA_STATUS_OK != res)
1094     {
1095         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1096         ca_thread_pool_free(g_threadPoolHandle);
1097         g_threadPoolHandle = NULL;
1098         return res;
1099     }
1100
1101     // start send thread
1102     res = CAQueueingThreadStart(&g_sendThread);
1103     if (CA_STATUS_OK != res)
1104     {
1105         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1106         ca_thread_pool_free(g_threadPoolHandle);
1107         g_threadPoolHandle = NULL;
1108         CAQueueingThreadDestroy(&g_sendThread);
1109         return res;
1110     }
1111
1112     // receive thread initialize
1113     res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1114                                      CAReceiveThreadProcess, CADestroyData);
1115     if (CA_STATUS_OK != res)
1116     {
1117         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1118         ca_thread_pool_free(g_threadPoolHandle);
1119         g_threadPoolHandle = NULL;
1120         CAQueueingThreadDestroy(&g_sendThread);
1121         return res;
1122     }
1123
1124 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1125     // start receive thread
1126     res = CAQueueingThreadStart(&g_receiveThread);
1127     if (CA_STATUS_OK != res)
1128     {
1129         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1130         ca_thread_pool_free(g_threadPoolHandle);
1131         g_threadPoolHandle = NULL;
1132         CAQueueingThreadDestroy(&g_sendThread);
1133         CAQueueingThreadDestroy(&g_receiveThread);
1134         return res;
1135     }
1136 #endif // SINGLE_HANDLE
1137
1138     // retransmission initialize
1139     res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1140                                      CASendUnicastData, CATimeoutCallback, NULL);
1141     if (CA_STATUS_OK != res)
1142     {
1143         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1144         ca_thread_pool_free(g_threadPoolHandle);
1145         g_threadPoolHandle = NULL;
1146         CAQueueingThreadDestroy(&g_sendThread);
1147         CAQueueingThreadDestroy(&g_receiveThread);
1148         return res;
1149     }
1150
1151 #ifdef WITH_BWT
1152     // block-wise transfer initialize
1153     res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1154     if (CA_STATUS_OK != res)
1155     {
1156         OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1157         ca_thread_pool_free(g_threadPoolHandle);
1158         g_threadPoolHandle = NULL;
1159         CAQueueingThreadDestroy(&g_sendThread);
1160         CAQueueingThreadDestroy(&g_receiveThread);
1161         CARetransmissionDestroy(&g_retransmissionContext);
1162         return res;
1163     }
1164 #endif
1165
1166     // start retransmission
1167     res = CARetransmissionStart(&g_retransmissionContext);
1168     if (CA_STATUS_OK != res)
1169     {
1170         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1171         ca_thread_pool_free(g_threadPoolHandle);
1172         g_threadPoolHandle = NULL;
1173         CAQueueingThreadDestroy(&g_sendThread);
1174         CAQueueingThreadDestroy(&g_receiveThread);
1175         CARetransmissionDestroy(&g_retransmissionContext);
1176         return res;
1177     }
1178
1179     // initialize interface adapters by controller
1180     CAInitializeAdapters(g_threadPoolHandle);
1181 #else
1182     // retransmission initialize
1183     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1184                                                 CATimeoutCallback, NULL);
1185     if (CA_STATUS_OK != res)
1186     {
1187         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1188         return res;
1189     }
1190
1191     CAInitializeAdapters();
1192 #endif // SINGLE_THREAD
1193
1194     return CA_STATUS_OK;
1195 }
1196
1197 void CATerminateMessageHandler()
1198 {
1199 #ifndef SINGLE_THREAD
1200     CATransportAdapter_t connType;
1201     u_arraylist_t *list = CAGetSelectedNetworkList();
1202     uint32_t length = u_arraylist_length(list);
1203
1204     uint32_t i = 0;
1205     for (i = 0; i < length; i++)
1206     {
1207         void* ptrType = u_arraylist_get(list, i);
1208
1209         if (NULL == ptrType)
1210         {
1211             continue;
1212         }
1213
1214         connType = *(CATransportAdapter_t *)ptrType;
1215         CAStopAdapter(connType);
1216     }
1217
1218     // stop retransmission
1219     if (NULL != g_retransmissionContext.threadMutex)
1220     {
1221         CARetransmissionStop(&g_retransmissionContext);
1222     }
1223
1224     // stop thread
1225     // delete thread data
1226     if (NULL != g_sendThread.threadMutex)
1227     {
1228         CAQueueingThreadStop(&g_sendThread);
1229     }
1230
1231     // stop thread
1232     // delete thread data
1233     if (NULL != g_receiveThread.threadMutex)
1234     {
1235 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1236         CAQueueingThreadStop(&g_receiveThread);
1237 #endif
1238     }
1239
1240     // destroy thread pool
1241     if (NULL != g_threadPoolHandle)
1242     {
1243         ca_thread_pool_free(g_threadPoolHandle);
1244         g_threadPoolHandle = NULL;
1245     }
1246
1247 #ifdef WITH_BWT
1248     CATerminateBlockWiseTransfer();
1249 #endif
1250     CARetransmissionDestroy(&g_retransmissionContext);
1251     CAQueueingThreadDestroy(&g_sendThread);
1252     CAQueueingThreadDestroy(&g_receiveThread);
1253
1254     // terminate interface adapters by controller
1255     CATerminateAdapters();
1256 #else
1257     // terminate interface adapters by controller
1258     CATerminateAdapters();
1259
1260     // stop retransmission
1261     CARetransmissionStop(&g_retransmissionContext);
1262     CARetransmissionDestroy(&g_retransmissionContext);
1263 #endif // SINGLE_THREAD
1264 }
1265
1266 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1267 {
1268     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1269     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1270
1271     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1272
1273 #ifdef WITH_TCP
1274     if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1275     {
1276         OIC_LOG(DEBUG, TAG, "pdu header data :");
1277         OIC_LOG_BUFFER(DEBUG, TAG,  (const uint8_t *) pdu->hdr, pdu->length);
1278     }
1279     else
1280 #endif
1281     {
1282         OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1283
1284         OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1285
1286         OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1287
1288         OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1289                        pdu->hdr->coap_hdr_udp_t.token_length);
1290     }
1291 }
1292
1293 static void CALogPayloadInfo(CAInfo_t *info)
1294 {
1295     if(info)
1296     {
1297         if (info->options)
1298         {
1299             for (uint32_t i = 0; i < info->numOptions; i++)
1300             {
1301                 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1302
1303                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1304             }
1305         }
1306
1307         if (info->payload)
1308         {
1309             OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1310                       info->payloadSize);
1311         }
1312
1313         if (info->token)
1314         {
1315             OIC_LOG(DEBUG, TAG, "token:");
1316             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1317                            info->tokenLength);
1318         }
1319         OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1320     }
1321     else
1322     {
1323         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1324     }
1325 }
1326
1327 void CAErrorHandler(const CAEndpoint_t *endpoint,
1328                     const void *data, uint32_t dataLen,
1329                     CAResult_t result)
1330 {
1331     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1332
1333 #ifndef SINGLE_THREAD
1334     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1335     VERIFY_NON_NULL_VOID(data, TAG, "data");
1336
1337     uint32_t code = CA_NOT_FOUND;
1338     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1339     //Get PDU data
1340     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1341     if (NULL == pdu)
1342     {
1343         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1344         return;
1345     }
1346
1347     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1348     if(!cadata)
1349     {
1350         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1351         coap_delete_pdu(pdu);
1352         return;
1353     }
1354
1355     cadata->errorInfo->result = result;
1356
1357     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1358     coap_delete_pdu(pdu);
1359 #endif
1360
1361     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1362     return;
1363 }
1364
1365 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1366 {
1367     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1368 #ifndef SINGLE_THREAD
1369     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1370     if (!cadata)
1371     {
1372         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1373         return;
1374     }
1375
1376     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1377     if (!ep)
1378     {
1379         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1380         OICFree(cadata);
1381         return;
1382     }
1383
1384     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1385     if (!errorInfo)
1386     {
1387         OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1388         OICFree(cadata);
1389         CAFreeEndpoint(ep);
1390         return;
1391     }
1392
1393     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1394     if (CA_STATUS_OK != res)
1395     {
1396         OIC_LOG(ERROR, TAG, "info clone failed");
1397         OICFree(cadata);
1398         OICFree(errorInfo);
1399         CAFreeEndpoint(ep);
1400         return;
1401     }
1402
1403     errorInfo->result = result;
1404     cadata->remoteEndpoint = ep;
1405     cadata->errorInfo = errorInfo;
1406     cadata->dataType = CA_ERROR_DATA;
1407
1408     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1409 #endif
1410     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1411 }