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