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