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