Hiding Privacy Logs for LUX
[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 #define SINGLE_HANDLE
52 #define MAX_THREAD_POOL_SIZE    20
53
54 #define UNUSED(x) (void)(x)
55
56 // thread pool handle
57 static ca_thread_pool_t g_threadPoolHandle = NULL;
58
59 // message handler main thread
60 static CAQueueingThread_t g_sendThread;
61 static CAQueueingThread_t g_receiveThread;
62
63 #else
64 #define CA_MAX_RT_ARRAY_SIZE    3
65 #endif  // SINGLE_THREAD
66
67 #define TAG "OIC_CA_MSG_HANDLE"
68
69 static CARetransmission_t g_retransmissionContext;
70
71 // handler field
72 static CARequestCallback g_requestHandler = NULL;
73 static CAResponseCallback g_responseHandler = NULL;
74 static CAErrorCallback g_errorHandler = NULL;
75 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
76
77 static void CAErrorHandler(const CAEndpoint_t *endpoint,
78                            const void *data, uint32_t dataLen,
79                            CAResult_t result);
80
81 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
82                                        const CARemoteId_t *identity,
83                                        const void *data, CADataType_t dataType);
84
85 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
86                             CAResult_t result);
87
88 #ifdef SINGLE_THREAD
89 static void CAProcessReceivedData(CAData_t *data);
90 #endif
91 static void CADestroyData(void *data, uint32_t size);
92 static void CALogPayloadInfo(CAInfo_t *info);
93 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
94                                 CAToken_t token, uint8_t tokenLength);
95
96 /**
97  * print send / receive message of CoAP.
98  * @param[in] data      CA information which has send/receive message and endpoint.
99  * @param[in] pdu       CoAP pdu low data.
100  */
101 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu);
102
103 #ifndef ARDUINO
104 static char g_headerBuffer[MAX_LOG_BUFFER_SIZE] = {0};
105 static size_t g_headerIndex = 0;
106 static void CASamsungLogMessage(const CAData_t *data, const coap_pdu_t *pdu);
107 #endif
108
109 #ifdef WITH_BWT
110 void CAAddDataToSendThread(CAData_t *data)
111 {
112     VERIFY_NON_NULL_VOID(data, TAG, "data");
113
114     // add thread
115     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
116 }
117
118 void CAAddDataToReceiveThread(CAData_t *data)
119 {
120     VERIFY_NON_NULL_VOID(data, TAG, "data");
121
122     // add thread
123     CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
124 }
125 #endif
126
127 static bool CAIsSelectedNetworkAvailable()
128 {
129     u_arraylist_t *list = CAGetSelectedNetworkList();
130     if (!list || u_arraylist_length(list) == 0)
131     {
132         OIC_LOG(ERROR, TAG, "No selected network");
133         return false;
134     }
135
136     return true;
137 }
138
139 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
140                                        const CARemoteId_t *identity,
141                                        const void *data, CADataType_t dataType)
142 {
143     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
144     CAInfo_t *info = NULL;
145     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
146     if (!cadata)
147     {
148         OIC_LOG(ERROR, TAG, "memory allocation failed");
149         return NULL;
150     }
151 #ifdef SINGLE_THREAD
152     CAEndpoint_t* ep = endpoint;
153 #else
154     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
155     if (!ep)
156     {
157         OIC_LOG(ERROR, TAG, "endpoint clone failed");
158         goto exit;
159     }
160 #endif
161
162     OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
163
164     if (CA_RESPONSE_DATA == dataType)
165     {
166         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
167         if (!resInfo)
168         {
169             OIC_LOG(ERROR, TAG, "memory allocation failed");
170             goto exit;
171         }
172
173         CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
174         if (CA_STATUS_OK != result)
175         {
176             OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
177             CADestroyResponseInfoInternal(resInfo);
178             goto exit;
179         }
180         cadata->responseInfo = resInfo;
181         info = &resInfo->info;
182         if (identity)
183         {
184             info->identity = *identity;
185         }
186         OIC_LOG(DEBUG, TAG, "Response Info :");
187         CALogPayloadInfo(info);
188     }
189     else if (CA_REQUEST_DATA == dataType)
190     {
191         CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
192         if (!reqInfo)
193         {
194             OIC_LOG(ERROR, TAG, "memory allocation failed");
195             goto exit;
196         }
197
198         CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
199         if (CA_STATUS_OK != result)
200         {
201             OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
202             CADestroyRequestInfoInternal(reqInfo);
203             goto exit;
204         }
205
206         if ((reqInfo->info.type != CA_MSG_CONFIRM) &&
207             CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
208                                 reqInfo->info.token, reqInfo->info.tokenLength))
209         {
210             OIC_LOG(INFO, TAG, "Second Request with same Token, Drop it");
211             CADestroyRequestInfoInternal(reqInfo);
212             goto exit;
213         }
214
215         cadata->requestInfo = reqInfo;
216         info = &reqInfo->info;
217         if (identity)
218         {
219             info->identity = *identity;
220         }
221         OIC_LOG(DEBUG, TAG, "Request Info :");
222         CALogPayloadInfo(info);
223    }
224     else if (CA_ERROR_DATA == dataType)
225     {
226         CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
227         if (!errorInfo)
228         {
229             OIC_LOG(ERROR, TAG, "Memory allocation failed!");
230             goto exit;
231         }
232
233         CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
234         if (CA_STATUS_OK != result)
235         {
236             OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
237             OICFree(errorInfo);
238             goto exit;
239         }
240
241         cadata->errorInfo = errorInfo;
242         info = &errorInfo->info;
243         if (identity)
244         {
245             info->identity = *identity;
246         }
247         OIC_LOG(DEBUG, TAG, "error Info :");
248         CALogPayloadInfo(info);
249     }
250
251     cadata->remoteEndpoint = ep;
252     cadata->dataType = dataType;
253
254     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
255     return cadata;
256
257 exit:
258     OICFree(cadata);
259 #ifndef SINGLE_THREAD
260     CAFreeEndpoint(ep);
261 #endif
262     return NULL;
263 }
264
265 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
266 {
267     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
268     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
269 #ifdef SINGLE_THREAD
270     CAEndpoint_t* ep = endpoint;
271 #else
272     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
273     if (!ep)
274     {
275         OIC_LOG(ERROR, TAG, "clone failed");
276         return;
277     }
278 #endif
279
280     CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
281
282     if (!resInfo)
283     {
284         OIC_LOG(ERROR, TAG, "calloc failed");
285 #ifndef SINGLE_THREAD
286         CAFreeEndpoint(ep);
287 #endif
288         return;
289     }
290
291     resInfo->result = CA_RETRANSMIT_TIMEOUT;
292     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
293     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
294
295     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *) pdu, &(resInfo->info),
296                                        endpoint);
297     if (CA_STATUS_OK != res)
298     {
299         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
300         CADestroyResponseInfoInternal(resInfo);
301 #ifndef SINGLE_THREAD
302         CAFreeEndpoint(ep);
303 #endif
304         return;
305     }
306
307     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
308     if (NULL == cadata)
309     {
310         OIC_LOG(ERROR, TAG, "memory allocation failed !");
311 #ifndef SINGLE_THREAD
312         CAFreeEndpoint(ep);
313 #endif
314         CADestroyResponseInfoInternal(resInfo);
315         return;
316     }
317
318     cadata->type = SEND_TYPE_UNICAST;
319     cadata->remoteEndpoint = ep;
320     cadata->requestInfo = NULL;
321     cadata->responseInfo = resInfo;
322
323 #ifdef WITH_BWT
324     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
325     {
326         res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
327                                                 endpoint->port);
328         if (CA_STATUS_OK != res)
329         {
330             OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
331         }
332     }
333 #endif // WITH_BWT
334
335 #ifdef SINGLE_THREAD
336     CAProcessReceivedData(cadata);
337 #else
338     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
339 #endif
340 }
341
342 static void CADestroyData(void *data, uint32_t size)
343 {
344     OIC_LOG(DEBUG, TAG, "CADestroyData IN");
345     if ((size_t)size < sizeof(CAData_t))
346     {
347         OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
348     }
349     CAData_t *cadata = (CAData_t *) data;
350
351     if (NULL == cadata)
352     {
353         OIC_LOG(ERROR, TAG, "cadata is NULL");
354         return;
355     }
356 #ifndef SINGLE_THREAD
357     if (NULL != cadata->remoteEndpoint)
358     {
359         CAFreeEndpoint(cadata->remoteEndpoint);
360     }
361 #endif
362
363     if (NULL != cadata->requestInfo)
364     {
365         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
366     }
367
368     if (NULL != cadata->responseInfo)
369     {
370         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
371     }
372
373     if (NULL != cadata->errorInfo)
374     {
375         CADestroyErrorInfoInternal(cadata->errorInfo);
376     }
377
378     OICFree(cadata);
379     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
380 }
381
382 #ifdef SINGLE_THREAD
383 static void CAProcessReceivedData(CAData_t *data)
384 {
385     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
386     if (!data)
387     {
388         OIC_LOG(ERROR, TAG, "thread data error!!");
389         return;
390     }
391
392     // parse the data and call the callbacks.
393     // #1 parse the data
394     // #2 get endpoint
395     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
396     if (!rep)
397     {
398         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
399         return;
400     }
401
402     if (data->requestInfo && g_requestHandler)
403     {
404         g_requestHandler(rep, data->requestInfo);
405     }
406     else if (data->responseInfo && g_responseHandler)
407     {
408         g_responseHandler(rep, data->responseInfo);
409     }
410     else if (data->errorInfo && g_errorHandler)
411     {
412         g_errorHandler(rep, data->errorInfo);
413     }
414
415     CADestroyData(data, sizeof(CAData_t));
416
417     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
418 }
419 #endif
420
421 #ifndef SINGLE_THREAD
422 static void CAReceiveThreadProcess(void *threadData)
423 {
424 #ifndef SINGLE_HANDLE
425     CAData_t *data = (CAData_t *) threadData;
426     OIC_TRACE_BEGIN(%s:CAProcessReceivedData, TAG);
427     CAProcessReceivedData(data);
428     OIC_TRACE_END();
429 #else
430     (void)threadData;
431 #endif
432 }
433 #endif // SINGLE_THREAD
434
435 static CAResult_t CAProcessMulticastData(const CAData_t *data)
436 {
437     VERIFY_NON_NULL(data, TAG, "data");
438     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
439
440     coap_pdu_t *pdu = NULL;
441     CAInfo_t *info = NULL;
442     coap_list_t *options = NULL;
443     coap_transport_t transport = COAP_UDP;
444     CAResult_t res = CA_SEND_FAILED;
445
446     if (!data->requestInfo && !data->responseInfo)
447     {
448         OIC_LOG(ERROR, TAG, "request or response info is empty");
449         return res;
450     }
451
452     if (data->requestInfo)
453     {
454         OIC_LOG(DEBUG, TAG, "requestInfo is available..");
455
456         info = &data->requestInfo->info;
457         pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
458     }
459     else if (data->responseInfo)
460     {
461         OIC_LOG(DEBUG, TAG, "responseInfo is available..");
462
463         info = &data->responseInfo->info;
464         pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
465                             &options, &transport);
466     }
467
468     if (!pdu)
469     {
470         OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
471         CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
472         coap_delete_list(options);
473         return res;
474     }
475
476 #ifdef WITH_BWT
477     if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
478     {
479         // Blockwise transfer
480         res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
481         if (CA_STATUS_OK != res)
482         {
483             OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
484             goto exit;
485         }
486     }
487 #endif // WITH_BWT
488
489     CALogPDUInfo(data, pdu);
490
491     res = CASendMulticastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
492     if (CA_STATUS_OK != res)
493     {
494         OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
495         goto exit;
496     }
497
498     coap_delete_list(options);
499     coap_delete_pdu(pdu);
500     return res;
501
502 exit:
503     CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
504     coap_delete_list(options);
505     coap_delete_pdu(pdu);
506     return res;
507 }
508
509 static CAResult_t CAProcessSendData(const CAData_t *data)
510 {
511     VERIFY_NON_NULL(data, TAG, "data");
512     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
513
514     CAResult_t res = CA_STATUS_FAILED;
515
516     if (CA_NETWORK_COMMAND == data->dataType)
517     {
518         if (CA_REQ_DISCONNECT == data->eventInfo)
519         {
520 #ifdef TCP_ADAPTER
521             // request TCP disconnect
522             if (CA_ADAPTER_TCP == data->remoteEndpoint->adapter)
523             {
524                 OIC_LOG(INFO, TAG, "request TCP disconnect");
525                 return CADisconnectSession(data->remoteEndpoint);
526             }
527 #endif
528         }
529     }
530
531     CASendDataType_t type = data->type;
532
533     coap_pdu_t *pdu = NULL;
534     CAInfo_t *info = NULL;
535     coap_list_t *options = NULL;
536     coap_transport_t transport = COAP_UDP;
537
538     if (SEND_TYPE_UNICAST == type)
539     {
540         OIC_LOG(DEBUG,TAG,"Unicast message");
541
542 #ifdef ROUTING_GATEWAY
543         /*
544          * When forwarding a packet, do not attempt retransmission as its the responsibility of
545          * packet originator node
546          */
547         bool skipRetransmission = false;
548 #endif
549
550         if (NULL != data->requestInfo)
551         {
552             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
553
554             info = &data->requestInfo->info;
555 #ifdef ROUTING_GATEWAY
556             skipRetransmission = data->requestInfo->info.skipRetransmission;
557 #endif
558             pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
559                                 &options, &transport);
560         }
561         else if (NULL != data->responseInfo)
562         {
563             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
564
565             info = &data->responseInfo->info;
566 #ifdef ROUTING_GATEWAY
567             skipRetransmission = data->responseInfo->info.skipRetransmission;
568 #endif
569             pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
570                                 &options, &transport);
571         }
572         else
573         {
574             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
575             return CA_STATUS_INVALID_PARAM;
576         }
577
578         // interface controller function call.
579         if (NULL != pdu)
580         {
581 #ifdef WITH_BWT
582             if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
583             {
584                 // Blockwise transfer
585                 if (NULL != info)
586                 {
587                     CAResult_t res = CAAddBlockOption(&pdu, info,
588                                                       data->remoteEndpoint,
589                                                       &options);
590                     if (CA_STATUS_OK != res)
591                     {
592                         OIC_LOG(INFO, TAG, "to write block option has failed");
593                         CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
594                         coap_delete_list(options);
595                         coap_delete_pdu(pdu);
596                         return res;
597                     }
598                 }
599             }
600 #endif // WITH_BWT
601             CALogPDUInfo(data, pdu);
602
603             OIC_LOG_V(INFO, TAG, "CASendUnicastData type : %d", data->dataType);
604             res = CASendUnicastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
605             if (CA_STATUS_OK != res)
606             {
607                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
608                 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
609                 coap_delete_list(options);
610                 coap_delete_pdu(pdu);
611                 return res;
612             }
613
614 #ifdef WITH_TCP
615             if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
616             {
617                 OIC_LOG(INFO, TAG, "retransmission will be not worked");
618             }
619             else
620 #endif
621 #ifdef ROUTING_GATEWAY
622             if (!skipRetransmission)
623 #endif
624             {
625                 // for retransmission
626                 res = CARetransmissionSentData(&g_retransmissionContext,
627                                                data->remoteEndpoint,
628                                                data->dataType,
629                                                pdu->transport_hdr, pdu->length);
630                 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
631                 {
632                     //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
633                     OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
634                     coap_delete_list(options);
635                     coap_delete_pdu(pdu);
636                     return res;
637                 }
638             }
639
640             coap_delete_list(options);
641             coap_delete_pdu(pdu);
642         }
643         else
644         {
645             OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
646             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
647             return CA_SEND_FAILED;
648         }
649     }
650     else if (SEND_TYPE_MULTICAST == type)
651     {
652         OIC_LOG(DEBUG,TAG,"Multicast message");
653 #ifdef WITH_TCP
654         /*
655          * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
656          * That's why we need to generate two pdu's, one for IP and second for other transports.
657          * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
658          * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
659          */
660         if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
661                 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
662                     CA_ADAPTER_IP != data->remoteEndpoint->adapter))
663         {
664             if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
665             {
666                 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
667             }
668             else
669             {
670                 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
671             }
672             CAProcessMulticastData(data);
673             data->remoteEndpoint->adapter = CA_ADAPTER_IP;
674             CAProcessMulticastData(data);
675         }
676         else
677         {
678             CAProcessMulticastData(data);
679         }
680 #else
681         CAProcessMulticastData(data);
682 #endif
683     }
684     return CA_STATUS_OK;
685 }
686
687 #ifndef SINGLE_THREAD
688 static void CASendThreadProcess(void *threadData)
689 {
690     CAData_t *data = (CAData_t *) threadData;
691     OIC_TRACE_BEGIN(%s:CAProcessSendData, TAG);
692     CAProcessSendData(data);
693     OIC_TRACE_END();
694 }
695 #endif
696
697 /*
698  * If a second message arrives with the same message ID, token and the other address
699  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
700  */
701 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
702                                 CAToken_t token, uint8_t tokenLength)
703 {
704     if (!ep)
705     {
706         return true;
707     }
708     if (ep->adapter != CA_ADAPTER_IP)
709     {
710         return false;
711     }
712     if (!caglobals.ip.dualstack)
713     {
714         return false;
715     }
716
717     if (tokenLength > CA_MAX_TOKEN_LEN)
718     {
719         /*
720          * If token length is more than CA_MAX_TOKEN_LEN,
721          * we compare the first CA_MAX_TOKEN_LEN bytes only.
722          */
723         tokenLength = CA_MAX_TOKEN_LEN;
724     }
725
726     bool ret = false;
727     CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
728
729     for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
730     {
731         CAHistoryItem_t *item = &(history->items[i]);
732         if (id == item->messageId && tokenLength == item->tokenLength
733             && memcmp(item->token, token, tokenLength) == 0)
734         {
735             if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
736             {
737                 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
738                           familyFlags & CA_IPV6 ? '6' : '4');
739                 ret = true;
740                 break;
741             }
742         }
743     }
744
745     history->items[history->nextIndex].flags = familyFlags;
746     history->items[history->nextIndex].messageId = id;
747     if (token && tokenLength)
748     {
749         memcpy(history->items[history->nextIndex].token, token, tokenLength);
750         history->items[history->nextIndex].tokenLength = tokenLength;
751     }
752
753     if (++history->nextIndex >= HISTORYSIZE)
754     {
755         history->nextIndex = 0;
756     }
757
758     return ret;
759 }
760
761 static CAResult_t CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
762                                            const void *data, uint32_t dataLen)
763 {
764     VERIFY_NON_NULL(sep, TAG, "remoteEndpoint");
765     VERIFY_NON_NULL(data, TAG, "data");
766     OIC_TRACE_BEGIN(%s:CAReceivedPacketCallback, TAG);
767
768     if (0 == dataLen)
769     {
770         OIC_LOG(ERROR, TAG, "dataLen is zero");
771         OIC_TRACE_END();
772
773         return CA_STATUS_FAILED;
774     }
775
776     // samsung log
777     OIC_LOG(DEBUG, TAG, "received pdu data :");
778     if (dataLen < 32)
779     {
780         OIC_LOG_BUFFER(DEBUG, TAG,  data, dataLen);
781     }
782     else
783     {
784         OIC_LOG_BUFFER(DEBUG, TAG,  data, 32);
785     }
786
787     CAResult_t res = CA_STATUS_OK;
788     uint32_t code = CA_NOT_FOUND;
789     CAData_t *cadata = NULL;
790
791     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
792                                                 &(sep->endpoint));
793     if (NULL == pdu)
794     {
795         OIC_LOG(ERROR, TAG, "Parse PDU failed");
796         res = CA_STATUS_FAILED;
797         goto exit;
798     }
799
800     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
801     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
802     {
803         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
804         if (!cadata)
805         {
806             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
807             coap_delete_pdu(pdu);
808             goto exit;
809         }
810     }
811     else
812     {
813         cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
814         if (!cadata)
815         {
816             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
817             coap_delete_pdu(pdu);
818             goto exit;
819         }
820
821 #ifdef WITH_TCP
822         if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
823         {
824             OIC_LOG(INFO, TAG, "retransmission is not supported");
825         }
826         else
827 #endif
828         {
829             // for retransmission
830             void *retransmissionPdu = NULL;
831             CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->transport_hdr,
832                                          pdu->length, &retransmissionPdu);
833
834             // get token from saved data in retransmission list
835             if (retransmissionPdu && CA_EMPTY == code)
836             {
837                 if (cadata->responseInfo)
838                 {
839                     CAInfo_t *info = &cadata->responseInfo->info;
840                     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *)retransmissionPdu,
841                                                        info, &(sep->endpoint));
842                     if (CA_STATUS_OK != res)
843                     {
844                         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
845                         OICFree(info->token);
846                         info->tokenLength = 0;
847                     }
848                 }
849             }
850             OICFree(retransmissionPdu);
851         }
852     }
853
854     cadata->type = SEND_TYPE_UNICAST;
855
856     CALogPDUInfo(cadata, pdu);
857
858 #ifdef SINGLE_THREAD
859     CAProcessReceivedData(cadata);
860 #else
861 #ifdef WITH_BWT
862     if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
863     {
864         CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
865         if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
866         {
867             OIC_LOG(DEBUG, TAG, "this message does not have block option");
868             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
869         }
870         else
871         {
872             CADestroyData(cadata, sizeof(CAData_t));
873         }
874     }
875     else
876 #endif
877     {
878         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
879     }
880 #endif // SINGLE_THREAD
881
882     coap_delete_pdu(pdu);
883
884 exit:
885     OIC_LOG(DEBUG, TAG, "OUT - Recv Thread");
886     OIC_TRACE_END();
887     return res;
888 }
889
890 static void CAAdapterStateChangedCallback(CATransportAdapter_t transportType, bool enabled)
891 {
892     if (!enabled)
893     {
894         CAClearMessageHandler(transportType);
895     }
896 }
897
898 static bool CAClearQueueEndpointDataContext(void *data, uint32_t size, void *ctx)
899 {
900     UNUSED(size);
901     if (NULL == data || NULL == ctx)
902     {
903         return false;
904     }
905
906     CAData_t *caData = (CAData_t *)data;
907     const CAEndpoint_t *endpoint = (const CAEndpoint_t *)ctx;
908
909     if (NULL != caData && NULL != caData->remoteEndpoint)
910     {
911         if (strcmp(caData->remoteEndpoint->addr, endpoint->addr) == 0
912             && caData->remoteEndpoint->port == endpoint->port
913             && caData->remoteEndpoint->adapter == endpoint->adapter)
914         {
915             return true;
916         }
917     }
918     return false;
919 }
920
921 static void CAConnectionStateChangedCallback(const CAEndpoint_t *info, bool isConnected)
922 {
923     if (!isConnected)
924     {
925         CAResult_t res = CAQueueingThreadClearContextData(&g_sendThread,
926                                                           CAClearQueueEndpointDataContext,
927                                                           (void *)info);
928         if (CA_STATUS_OK != res)
929         {
930             OIC_LOG(ERROR, TAG, "Could not clear the send queue");
931         }
932     }
933 }
934
935 void CAHandleRequestResponseCallbacks()
936 {
937 #ifdef SINGLE_THREAD
938     CAReadData();
939     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
940 #else
941 #ifdef SINGLE_HANDLE
942     // parse the data and call the callbacks.
943     // #1 parse the data
944     // #2 get endpoint
945
946     oc_mutex_lock(g_receiveThread.threadMutex);
947
948     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
949
950     oc_mutex_unlock(g_receiveThread.threadMutex);
951
952     if (NULL == item || NULL == item->msg)
953     {
954         return;
955     }
956
957     // get endpoint
958     CAData_t *td = (CAData_t *) item->msg;
959
960     if (td->requestInfo && g_requestHandler)
961     {
962         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
963         g_requestHandler(td->remoteEndpoint, td->requestInfo);
964     }
965     else if (td->responseInfo && g_responseHandler)
966     {
967         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
968         g_responseHandler(td->remoteEndpoint, td->responseInfo);
969     }
970     else if (td->errorInfo && g_errorHandler)
971     {
972         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
973         g_errorHandler(td->remoteEndpoint, td->errorInfo);
974     }
975
976     CADestroyData(item->msg, sizeof(CAData_t));
977     OICFree(item);
978
979 #endif // SINGLE_HANDLE
980 #endif // SINGLE_THREAD
981 }
982
983 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
984                                    CADataType_t dataType)
985 {
986     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
987
988     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
989     if (!cadata)
990     {
991         OIC_LOG(ERROR, TAG, "memory allocation failed");
992         return NULL;
993     }
994
995     if (CA_REQUEST_DATA == dataType)
996     {
997 #ifdef SINGLE_THREAD
998         CARequestInfo_t *request = (CARequestInfo_t *)sendData;
999 #else
1000         // clone request info
1001         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
1002         if (!request)
1003         {
1004             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
1005             goto exit;
1006         }
1007 #endif
1008         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
1009         cadata->requestInfo =  request;
1010     }
1011     else if (CA_RESPONSE_DATA == dataType || CA_RESPONSE_FOR_RES == dataType)
1012     {
1013 #ifdef SINGLE_THREAD
1014         CAResponseInfo_t *response = (CAResponseInfo_t *)sendData;
1015 #else
1016         // clone response info
1017         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
1018         if (!response)
1019         {
1020             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
1021             goto exit;
1022         }
1023 #endif
1024         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
1025         cadata->responseInfo = response;
1026     }
1027     else
1028     {
1029         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
1030         goto exit;
1031     }
1032
1033 #ifdef SINGLE_THREAD
1034     CAEndpoint_t* ep = endpoint;
1035 #else
1036     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1037     if (!ep)
1038     {
1039         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1040         goto exit;
1041     }
1042 #endif
1043     cadata->remoteEndpoint = ep;
1044     cadata->dataType = dataType;
1045     return cadata;
1046
1047 exit:
1048 #ifndef SINGLE_THREAD
1049     CADestroyData(cadata, sizeof(CAData_t));
1050 #else
1051     OICFree(cadata);
1052 #endif
1053     return NULL;
1054 }
1055
1056 CAResult_t CADetachSendNetworkReqMessage(const CAEndpoint_t *endpoint,
1057                                          CAConnectEvent_t event,
1058                                          CADataType_t dataType)
1059 {
1060     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1061
1062     if (false == CAIsSelectedNetworkAvailable())
1063     {
1064         return CA_STATUS_FAILED;
1065     }
1066
1067 #ifndef SINGLE_THREAD
1068     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1069     if (!cadata)
1070     {
1071         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1072         return CA_STATUS_FAILED;
1073     }
1074
1075     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1076     if (!ep)
1077     {
1078         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1079         OICFree(cadata);
1080         return CA_STATUS_FAILED;
1081     }
1082
1083     cadata->remoteEndpoint = ep;
1084     cadata->eventInfo = event;
1085     cadata->dataType = dataType;
1086
1087     CAQueueingThreadAddData(&g_sendThread, cadata, sizeof(CAData_t));
1088 #endif
1089
1090     return CA_STATUS_OK;
1091 }
1092
1093 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
1094                                CADataType_t dataType)
1095 {
1096     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1097     VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
1098
1099     if (false == CAIsSelectedNetworkAvailable())
1100     {
1101         return CA_STATUS_FAILED;
1102     }
1103
1104 #ifdef ARDUINO
1105     // If max retransmission queue is reached, then don't handle new request
1106     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
1107     {
1108         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
1109         return CA_SEND_FAILED;
1110     }
1111 #endif // ARDUINO
1112
1113     CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
1114     if(!data)
1115     {
1116         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
1117         return CA_MEMORY_ALLOC_FAILED;
1118     }
1119
1120     OIC_LOG_V(INFO_PRIVATE, TAG, "DID of endpoint of this message is %s", endpoint->remoteId);
1121
1122 #ifdef SINGLE_THREAD
1123     CAResult_t result = CAProcessSendData(data);
1124     if (CA_STATUS_OK != result)
1125     {
1126         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1127         OICFree(data);
1128         return result;
1129     }
1130
1131     OICFree(data);
1132
1133 #else
1134 #ifdef WITH_BWT
1135     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
1136     {
1137         CACheckAndDeleteTimedOutBlockData();
1138         // send block data
1139         CAResult_t res = CASendBlockWiseData(data);
1140         if (CA_NOT_SUPPORTED == res)
1141         {
1142             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1143             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1144             return CA_STATUS_OK;
1145         }
1146         else
1147         {
1148             CADestroyData(data, sizeof(CAData_t));
1149         }
1150
1151         return res;
1152     }
1153     else
1154 #endif // WITH_BWT
1155     {
1156         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1157     }
1158 #endif // SINGLE_THREAD
1159
1160     return CA_STATUS_OK;
1161 }
1162
1163 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1164                              CAErrorCallback errorHandler)
1165 {
1166     g_requestHandler = ReqHandler;
1167     g_responseHandler = RespHandler;
1168     g_errorHandler = errorHandler;
1169 }
1170
1171 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1172 {
1173     g_nwMonitorHandler = nwMonitorHandler;
1174 }
1175
1176 CAResult_t CAInitializeMessageHandler(CATransportAdapter_t transportType)
1177 {
1178     CASetPacketReceivedCallback((CANetworkPacketReceivedCallback)CAReceivedPacketCallback);
1179     CASetErrorHandleCallback((CAErrorHandleCallback)CAErrorHandler);
1180
1181 #ifndef SINGLE_THREAD
1182     // create thread pool
1183     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1184     if (CA_STATUS_OK != res)
1185     {
1186         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1187         return res;
1188     }
1189
1190     // send thread initialize
1191     res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1192                                      CASendThreadProcess, CADestroyData);
1193     if (CA_STATUS_OK != res)
1194     {
1195         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1196         return res;
1197     }
1198
1199     // start send thread
1200 #ifndef __TIZENRT__
1201     res = CAQueueingThreadStart(&g_sendThread);
1202 #else
1203     res = CAQueueingThreadStart(&g_sendThread, "IoT_MessageHandlerQueue");
1204 #endif
1205     if (CA_STATUS_OK != res)
1206     {
1207         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1208         return res;
1209     }
1210
1211     // receive thread initialize
1212     res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1213                                      CAReceiveThreadProcess, CADestroyData);
1214     if (CA_STATUS_OK != res)
1215     {
1216         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1217         return res;
1218     }
1219
1220 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1221     // start receive thread
1222     res = CAQueueingThreadStart(&g_receiveThread);
1223     if (CA_STATUS_OK != res)
1224     {
1225         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1226         return res;
1227     }
1228 #endif // SINGLE_HANDLE
1229
1230     // retransmission initialize
1231     res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1232                                      CASendUnicastData, CATimeoutCallback, NULL);
1233     if (CA_STATUS_OK != res)
1234     {
1235         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1236         return res;
1237     }
1238
1239 #ifdef WITH_BWT
1240     // block-wise transfer initialize
1241     res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1242     if (CA_STATUS_OK != res)
1243     {
1244         OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1245         return res;
1246     }
1247 #endif
1248
1249     // start retransmission
1250     res = CARetransmissionStart(&g_retransmissionContext);
1251     if (CA_STATUS_OK != res)
1252     {
1253         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1254         return res;
1255     }
1256
1257     // initialize interface adapters by controller
1258     CAInitializeAdapters(g_threadPoolHandle, transportType);
1259     CASetNetworkMonitorCallbacks(CAAdapterStateChangedCallback, CAConnectionStateChangedCallback);
1260 #else
1261     // retransmission initialize
1262     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1263                                                 CATimeoutCallback, NULL);
1264     if (CA_STATUS_OK != res)
1265     {
1266         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1267         return res;
1268     }
1269
1270     CAInitializeAdapters();
1271 #endif // SINGLE_THREAD
1272
1273     return CA_STATUS_OK;
1274 }
1275
1276 static bool CAClearQueueAdapterDataContext(void *data, uint32_t size, void *ctx)
1277 {
1278     (void)size;
1279
1280     if (NULL == data || NULL == ctx)
1281     {
1282         return false;
1283     }
1284
1285     CAData_t *caData = (CAData_t *)data;
1286     CATransportAdapter_t *type = (CATransportAdapter_t *)ctx;
1287
1288     if (NULL != caData && NULL != caData->remoteEndpoint
1289         && caData->remoteEndpoint->adapter == *type)
1290     {
1291         return true;
1292     }
1293     return false;
1294 }
1295
1296 void CAClearMessageHandler(CATransportAdapter_t transportType)
1297 {
1298     CATransportAdapter_t *typeCtx = &transportType;
1299
1300     CAResult_t res = CAQueueingThreadClearContextData(&g_sendThread,
1301                                                       CAClearQueueAdapterDataContext,
1302                                                       typeCtx);
1303
1304     if (res != CA_STATUS_OK)
1305     {
1306         OIC_LOG_V(ERROR, TAG, "Clear send data failed[%d]", res);
1307     }
1308
1309     if (transportType & DEFAULT_RETRANSMISSION_TYPE)
1310     {
1311         res = CARetransmissionClearAdapterData(&g_retransmissionContext, transportType);
1312         if (res != CA_STATUS_OK)
1313         {
1314             OIC_LOG_V(ERROR, TAG, "Clear retransmission data failed[%d]", res);
1315         }
1316     }
1317 }
1318
1319 void CATerminateMessageHandler()
1320 {
1321 #ifndef SINGLE_THREAD
1322     CATransportAdapter_t connType;
1323     u_arraylist_t *list = CAGetSelectedNetworkList();
1324     uint32_t length = u_arraylist_length(list);
1325
1326     uint32_t i = 0;
1327     for (i = 0; i < length; i++)
1328     {
1329         void* ptrType = u_arraylist_get(list, i);
1330
1331         if (NULL == ptrType)
1332         {
1333             continue;
1334         }
1335
1336         connType = *(CATransportAdapter_t *)ptrType;
1337         CAStopAdapter(connType);
1338     }
1339
1340     // stop retransmission
1341     if (NULL != g_retransmissionContext.threadMutex)
1342     {
1343         CARetransmissionStop(&g_retransmissionContext);
1344     }
1345
1346     // stop thread
1347     // delete thread data
1348     if (NULL != g_sendThread.threadMutex)
1349     {
1350         CAQueueingThreadStop(&g_sendThread);
1351     }
1352
1353     // stop thread
1354     // delete thread data
1355     if (NULL != g_receiveThread.threadMutex)
1356     {
1357 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1358         CAQueueingThreadStop(&g_receiveThread);
1359 #endif
1360     }
1361
1362     // destroy thread pool
1363     if (NULL != g_threadPoolHandle)
1364     {
1365         ca_thread_pool_free(g_threadPoolHandle);
1366         g_threadPoolHandle = NULL;
1367     }
1368
1369 #ifdef WITH_BWT
1370     CATerminateBlockWiseTransfer();
1371 #endif
1372     CARetransmissionDestroy(&g_retransmissionContext);
1373     CAQueueingThreadDestroy(&g_sendThread);
1374     CAQueueingThreadDestroy(&g_receiveThread);
1375
1376     // terminate interface adapters by controller
1377     CATerminateAdapters();
1378 #else
1379     // terminate interface adapters by controller
1380     CATerminateAdapters();
1381
1382     // stop retransmission
1383     CARetransmissionStop(&g_retransmissionContext);
1384     CARetransmissionDestroy(&g_retransmissionContext);
1385 #endif // SINGLE_THREAD
1386 }
1387
1388 static void CALogPayloadInfo(CAInfo_t *info)
1389 {
1390     if (info)
1391     {
1392         if (info->options)
1393         {
1394             for (uint32_t i = 0; i < info->numOptions; i++)
1395             {
1396                 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1397
1398                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1399             }
1400         }
1401
1402         if (info->payload)
1403         {
1404             OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1405                       info->payloadSize);
1406         }
1407
1408         if (info->token)
1409         {
1410             OIC_LOG(DEBUG, TAG, "token:");
1411             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1412                            info->tokenLength);
1413         }
1414         OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1415     }
1416     else
1417     {
1418         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1419     }
1420 }
1421
1422 void CAErrorHandler(const CAEndpoint_t *endpoint,
1423                     const void *data, uint32_t dataLen,
1424                     CAResult_t result)
1425 {
1426     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1427     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1428     VERIFY_NON_NULL_VOID(data, TAG, "data");
1429
1430     if (0 == dataLen)
1431     {
1432         OIC_LOG(ERROR, TAG, "dataLen is zero");
1433         return;
1434     }
1435
1436 #ifndef SINGLE_THREAD
1437     uint32_t code = CA_NOT_FOUND;
1438     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1439     //Get PDU data
1440     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1441     if (NULL == pdu)
1442     {
1443         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1444         return;
1445     }
1446
1447     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1448     if (!cadata)
1449     {
1450         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1451         coap_delete_pdu(pdu);
1452         return;
1453     }
1454
1455     cadata->errorInfo->result = result;
1456
1457     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1458     coap_delete_pdu(pdu);
1459 #else
1460     (void)result;
1461 #endif
1462
1463     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1464     return;
1465 }
1466
1467 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1468 {
1469     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1470 #ifndef SINGLE_THREAD
1471     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1472     if (!cadata)
1473     {
1474         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1475         return;
1476     }
1477
1478     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1479     if (!ep)
1480     {
1481         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1482         OICFree(cadata);
1483         return;
1484     }
1485
1486     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1487     if (!errorInfo)
1488     {
1489         OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1490         OICFree(cadata);
1491         CAFreeEndpoint(ep);
1492         return;
1493     }
1494
1495     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1496     if (CA_STATUS_OK != res)
1497     {
1498         OIC_LOG(ERROR, TAG, "info clone failed");
1499         OICFree(cadata);
1500         OICFree(errorInfo);
1501         CAFreeEndpoint(ep);
1502         return;
1503     }
1504
1505     errorInfo->result = result;
1506     cadata->remoteEndpoint = ep;
1507     cadata->errorInfo = errorInfo;
1508     cadata->dataType = CA_ERROR_DATA;
1509
1510     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1511 #endif
1512     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1513 }
1514
1515
1516
1517 #ifndef ARDUINO
1518 #ifdef __TIZENRT__
1519 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1520 {
1521
1522         if(data == NULL || pdu == NULL)
1523         {
1524                 printf("INVALID INPUT, CALogPDUInfo FAIL\n");
1525         }
1526
1527         char type[30] = "";
1528
1529         switch(data->dataType)
1530         {
1531                 case CA_REQUEST_DATA:
1532                         strncpy(type, "\e[32mREQUEST  <<<<\e[m", 30);
1533                         break;
1534                 case CA_RESPONSE_DATA:
1535                         strncpy(type, "\e[36mRESPONSE >>>>\e[m", 30);
1536                         break;
1537                 case CA_ERROR_DATA:
1538                         strncpy(type, "ERROR", 30);
1539                         break;
1540                 case CA_RESPONSE_FOR_RES:
1541                         strncpy(type, "RESP_RES >>>>", 30);
1542                         break;
1543                 default:
1544                         snprintf(type, 30, "Type : %d", data->dataType);
1545                         break;
1546         }
1547
1548
1549         char method[20] = "";
1550         const CAInfo_t *info = NULL;
1551         if (NULL != data->requestInfo)
1552         {
1553                 switch(data->requestInfo->method)
1554                 {
1555                         case CA_GET:
1556                                 strncpy(method, "GET", 20);
1557                                 break;
1558                         case CA_POST:
1559                                 strncpy(method, "POST", 20);
1560                                 break;
1561                         case CA_PUT:
1562                                 strncpy(method, "PUT", 20);
1563                                 break;
1564                         case CA_DELETE:
1565                                 strncpy(method, "DEL", 20);
1566                                 break;
1567                         default:
1568                                 sprintf(method, "Method : %d", data->requestInfo->method);
1569                                 break;
1570                 }
1571                 info = &data->requestInfo->info;
1572         }
1573
1574         if(NULL != data->responseInfo)
1575         {
1576
1577                 sprintf(method, "result : %d", data->responseInfo->result);
1578                 info = &data->responseInfo->info;
1579         }
1580
1581
1582         char log_buffer[1024] = "";
1583         sprintf(log_buffer, "CA_LOG [%5d] | %-13s | %-12s | msg size : %4d | %s", pdu->transport_hdr->udp.id , type, method, pdu->length, info->resourceUri);
1584
1585         puts(log_buffer);
1586 }
1587
1588
1589 #else
1590
1591 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1592 {
1593     OIC_LOG(DEBUG, TAG, "CALogPDUInfo");
1594
1595     VERIFY_NON_NULL_VOID(data, TAG, "data");
1596     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1597     OIC_TRACE_BEGIN(%s:CALogPDUInfo, TAG);
1598
1599     OIC_LOG(INFO, ANALYZER_TAG, "=================================================");
1600     if(SEND_TYPE_MULTICAST == data->type)
1601     {
1602         OIC_LOG(INFO, ANALYZER_TAG, "Is Multicast = true");
1603     }
1604     else
1605     {
1606         OIC_LOG(INFO, ANALYZER_TAG, "Is Multicast = false");
1607     }
1608
1609     if (NULL != data->remoteEndpoint)
1610     {
1611         CALogAdapterTypeInfo(data->remoteEndpoint->adapter);
1612         OIC_LOG_V(DEBUG, ANALYZER_TAG, "Address = [%s]:[%d]", data->remoteEndpoint->addr,
1613                   data->remoteEndpoint->port);
1614     }
1615
1616     switch(data->dataType)
1617     {
1618         case CA_REQUEST_DATA:
1619             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_REQUEST_DATA]");
1620             break;
1621         case CA_RESPONSE_DATA:
1622             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_RESPONSE_DATA]");
1623             break;
1624         case CA_ERROR_DATA:
1625             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_ERROR_DATA]");
1626             break;
1627         case CA_RESPONSE_FOR_RES:
1628             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_RESPONSE_FOR_RES]");
1629             break;
1630         default:
1631             OIC_LOG_V(INFO, ANALYZER_TAG, "Data Type = [%d]", data->dataType);
1632             break;
1633     }
1634
1635     const CAInfo_t *info = NULL;
1636     if (NULL != data->requestInfo)
1637     {
1638         switch(data->requestInfo->method)
1639         {
1640             case CA_GET:
1641                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [GET]");
1642                 break;
1643             case CA_POST:
1644                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [POST]");
1645                 break;
1646             case CA_PUT:
1647                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [PUT]");
1648                 break;
1649             case CA_DELETE:
1650                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [DELETE]");
1651                 break;
1652             default:
1653                 OIC_LOG_V(INFO, ANALYZER_TAG, "Method = [%d]", data->requestInfo->method);
1654                 break;
1655         }
1656         info = &data->requestInfo->info;
1657     }
1658
1659     if (NULL != data->responseInfo)
1660     {
1661         OIC_LOG_V(INFO, ANALYZER_TAG, "result code = [%d]", data->responseInfo->result);
1662         info = &data->responseInfo->info;
1663     }
1664
1665     if (pdu->transport_hdr)
1666     {
1667         OIC_LOG_V(INFO, ANALYZER_TAG, "Msg ID = [%d]", pdu->transport_hdr->udp.id);
1668     }
1669
1670     if (info)
1671     {
1672         OIC_LOG(INFO, ANALYZER_TAG, "Coap Token");
1673         OIC_LOG_BUFFER(INFO, ANALYZER_TAG, (const uint8_t *) info->token, info->tokenLength);
1674         OIC_TRACE_BUFFER("OIC_CA_MSG_HANDLE:CALogPDUInfo:token",
1675                          (const uint8_t *) info->token, info->tokenLength);
1676         OIC_LOG_V(INFO_PRIVATE, ANALYZER_TAG, "Res URI = [%s]", info->resourceUri);
1677         OIC_TRACE_MARK(%s:CALogPDUInfo:uri:%s, TAG, info->resourceUri);
1678
1679         if (CA_FORMAT_APPLICATION_CBOR == info->payloadFormat)
1680         {
1681             OIC_LOG(INFO, ANALYZER_TAG, "Payload Format = [CA_FORMAT_APPLICATION_CBOR]");
1682         }
1683         else
1684         {
1685             OIC_LOG_V(INFO, ANALYZER_TAG, "Payload Format = [%d]", info->payloadFormat);
1686         }
1687     }
1688
1689     size_t payloadLen = (pdu->data) ? (unsigned char *) pdu->hdr + pdu->length - pdu->data : 0;
1690     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Message Full Size = [%u]", pdu->length);
1691     OIC_LOG(INFO, ANALYZER_TAG, "CoAP Header (+ 0xFF)");
1692     OIC_LOG_BUFFER(INFO, ANALYZER_TAG,  (const uint8_t *) pdu->transport_hdr,
1693                    pdu->length - payloadLen);
1694     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Header size = [%" PRIuPTR "]", (size_t) pdu->length - payloadLen);
1695
1696     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Payload");
1697     OIC_LOG_BUFFER(INFO_PRIVATE, ANALYZER_TAG, pdu->data, payloadLen);
1698     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Payload Size = [%" PRIuPTR "]", payloadLen);
1699     OIC_LOG(INFO, ANALYZER_TAG, "=================================================");
1700
1701     // samsung log
1702     CASamsungLogMessage(data, pdu);
1703     OIC_TRACE_END();
1704 }
1705
1706 static void CASamsungLogMessage(const CAData_t *data, const coap_pdu_t *pdu)
1707 {
1708     OIC_LOG(INFO, TAG, "CASamsungLogMessage");
1709     VERIFY_NON_NULL_VOID(data, TAG, "data");
1710     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1711     VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "data->remoteEndpoint");
1712
1713     const CAInfo_t *info = NULL;
1714     if (NULL != data->requestInfo)
1715     {
1716         info = &data->requestInfo->info;
1717     }
1718
1719     if (NULL != data->responseInfo)
1720     {
1721         info = &data->responseInfo->info;
1722     }
1723
1724     VERIFY_NON_NULL_VOID(info, TAG, "info");
1725
1726     memset(g_headerBuffer, 0, MAX_LOG_BUFFER_SIZE);
1727     g_headerIndex = 0;
1728
1729     g_headerBuffer[g_headerIndex++] = data->dataType;
1730     g_headerBuffer[g_headerIndex++] = '|';
1731     g_headerBuffer[g_headerIndex++] = data->remoteEndpoint->adapter;
1732     g_headerBuffer[g_headerIndex++] = '|';
1733     g_headerBuffer[g_headerIndex++] = data->type;
1734     g_headerBuffer[g_headerIndex++] = '|';
1735
1736     if (NULL != data->remoteEndpoint)
1737     {
1738         int i = 0;
1739         while (data->remoteEndpoint->addr[i])
1740         {
1741             g_headerBuffer[g_headerIndex++] = data->remoteEndpoint->addr[i];
1742             i++;
1743         }
1744         g_headerBuffer[g_headerIndex++] = ':';
1745         g_headerBuffer[g_headerIndex++] = (data->remoteEndpoint->port >> 8) & 0x0000ff;
1746         g_headerBuffer[g_headerIndex++] = data->remoteEndpoint->port & 0x000000ff;
1747     }
1748
1749     g_headerBuffer[g_headerIndex++] = '|';
1750     if (data->requestInfo)
1751     {
1752         g_headerBuffer[g_headerIndex++] = data->requestInfo->method;
1753     }
1754     else
1755     {
1756         g_headerBuffer[g_headerIndex++] = 0;
1757     }
1758
1759     g_headerBuffer[g_headerIndex++] = '|';
1760     if (data->responseInfo)
1761     {
1762         g_headerBuffer[g_headerIndex++] = data->responseInfo->result;
1763     }
1764     else
1765     {
1766         g_headerBuffer[g_headerIndex++] = 0;
1767     }
1768     g_headerBuffer[g_headerIndex++] = '|';
1769
1770     if (pdu->transport_hdr)
1771     {
1772         g_headerBuffer[g_headerIndex++] = (pdu->transport_hdr->udp.id >> 8) & 0x0000ff;
1773         g_headerBuffer[g_headerIndex++] = pdu->transport_hdr->udp.id & 0x000000ff;
1774     }
1775     else
1776     {
1777         g_headerBuffer[g_headerIndex++] = 0;
1778         g_headerBuffer[g_headerIndex++] = 0;
1779     }
1780     g_headerBuffer[g_headerIndex++] = '|';
1781
1782     if (info->token && info->tokenLength > 0)
1783     {
1784         for (size_t i = 0; i < info->tokenLength; i++)
1785         {
1786             g_headerBuffer[g_headerIndex++] = info->token[i];
1787         }
1788         g_headerBuffer[g_headerIndex++] = '|';
1789     }
1790
1791     if (info->resourceUri)
1792     {
1793         size_t i = 0;
1794         while (info->resourceUri[i])
1795         {
1796             g_headerBuffer[g_headerIndex++] = info->resourceUri[i];
1797             i++;
1798         }
1799         g_headerBuffer[g_headerIndex++] = '|';
1800     }
1801
1802     OIC_LOG_CA_BUFFER(INFO, TAG, (uint8_t *) g_headerBuffer, g_headerIndex, 1);
1803     size_t payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1804     OIC_LOG_CA_BUFFER(INFO_PRIVATE, TAG, pdu->data, payloadLen, 0);
1805 }
1806 #endif
1807
1808 #else
1809 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1810 {
1811     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1812     (void)data;
1813
1814     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1815     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->transport_hdr->udp.type);
1816     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->transport_hdr->udp.code);
1817     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1818     OIC_LOG_BUFFER(DEBUG, TAG, pdu->transport_hdr->udp.token,
1819                    pdu->transport_hdr->udp.token_length);
1820 }
1821 #endif