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