Update snapshot(2017-12-14)
[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     (void)size;
899
900     if (NULL == data || NULL == ctx)
901     {
902         return false;
903     }
904
905     CAData_t *caData = (CAData_t *)data;
906     const CAEndpoint_t *endpoint = (const CAEndpoint_t *)ctx;
907
908     if (NULL != caData && NULL != caData->remoteEndpoint)
909     {
910         if (strcmp(caData->remoteEndpoint->addr, endpoint->addr) == 0
911             && caData->remoteEndpoint->port == endpoint->port
912             && caData->remoteEndpoint->adapter == endpoint->adapter)
913         {
914             return true;
915         }
916     }
917     return false;
918 }
919
920 static void CAConnectionStateChangedCallback(const CAEndpoint_t *info, bool isConnected)
921 {
922     if (!isConnected)
923     {
924         CAResult_t res = CAQueueingThreadClearContextData(&g_sendThread,
925                                                           CAClearQueueEndpointDataContext,
926                                                           (void *)info);
927         if (CA_STATUS_OK != res)
928         {
929             OIC_LOG(ERROR, TAG, "Could not clear the send queue");
930         }
931     }
932 }
933
934 void CAHandleRequestResponseCallbacks()
935 {
936 #ifdef SINGLE_THREAD
937     CAReadData();
938     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
939 #else
940 #ifdef SINGLE_HANDLE
941     // parse the data and call the callbacks.
942     // #1 parse the data
943     // #2 get endpoint
944
945     oc_mutex_lock(g_receiveThread.threadMutex);
946
947     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
948
949     oc_mutex_unlock(g_receiveThread.threadMutex);
950
951     if (NULL == item || NULL == item->msg)
952     {
953         return;
954     }
955
956     // get endpoint
957     CAData_t *td = (CAData_t *) item->msg;
958
959     if (td->requestInfo && g_requestHandler)
960     {
961         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
962         g_requestHandler(td->remoteEndpoint, td->requestInfo);
963     }
964     else if (td->responseInfo && g_responseHandler)
965     {
966         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
967         g_responseHandler(td->remoteEndpoint, td->responseInfo);
968     }
969     else if (td->errorInfo && g_errorHandler)
970     {
971         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
972         g_errorHandler(td->remoteEndpoint, td->errorInfo);
973     }
974
975     CADestroyData(item->msg, sizeof(CAData_t));
976     OICFree(item);
977
978 #endif // SINGLE_HANDLE
979 #endif // SINGLE_THREAD
980 }
981
982 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
983                                    CADataType_t dataType)
984 {
985     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
986
987     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
988     if (!cadata)
989     {
990         OIC_LOG(ERROR, TAG, "memory allocation failed");
991         return NULL;
992     }
993
994     if (CA_REQUEST_DATA == dataType)
995     {
996 #ifdef SINGLE_THREAD
997         CARequestInfo_t *request = (CARequestInfo_t *)sendData;
998 #else
999         // clone request info
1000         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
1001         if (!request)
1002         {
1003             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
1004             goto exit;
1005         }
1006 #endif
1007         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
1008         cadata->requestInfo =  request;
1009     }
1010     else if (CA_RESPONSE_DATA == dataType || CA_RESPONSE_FOR_RES == dataType)
1011     {
1012 #ifdef SINGLE_THREAD
1013         CAResponseInfo_t *response = (CAResponseInfo_t *)sendData;
1014 #else
1015         // clone response info
1016         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
1017         if (!response)
1018         {
1019             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
1020             goto exit;
1021         }
1022 #endif
1023         cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
1024         cadata->responseInfo = response;
1025     }
1026     else
1027     {
1028         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
1029         goto exit;
1030     }
1031
1032 #ifdef SINGLE_THREAD
1033     CAEndpoint_t* ep = endpoint;
1034 #else
1035     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1036     if (!ep)
1037     {
1038         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1039         goto exit;
1040     }
1041 #endif
1042     cadata->remoteEndpoint = ep;
1043     cadata->dataType = dataType;
1044     return cadata;
1045
1046 exit:
1047 #ifndef SINGLE_THREAD
1048     CADestroyData(cadata, sizeof(CAData_t));
1049 #else
1050     OICFree(cadata);
1051 #endif
1052     return NULL;
1053 }
1054
1055 CAResult_t CADetachSendNetworkReqMessage(const CAEndpoint_t *endpoint,
1056                                          CAConnectEvent_t event,
1057                                          CADataType_t dataType)
1058 {
1059     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1060
1061     if (false == CAIsSelectedNetworkAvailable())
1062     {
1063         return CA_STATUS_FAILED;
1064     }
1065
1066 #ifndef SINGLE_THREAD
1067     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1068     if (!cadata)
1069     {
1070         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1071         return CA_STATUS_FAILED;
1072     }
1073
1074     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1075     if (!ep)
1076     {
1077         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1078         OICFree(cadata);
1079         return CA_STATUS_FAILED;
1080     }
1081
1082     cadata->remoteEndpoint = ep;
1083     cadata->eventInfo = event;
1084     cadata->dataType = dataType;
1085
1086     CAQueueingThreadAddData(&g_sendThread, cadata, sizeof(CAData_t));
1087 #endif
1088
1089     return CA_STATUS_OK;
1090 }
1091
1092 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
1093                                CADataType_t dataType)
1094 {
1095     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1096     VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
1097
1098     if (false == CAIsSelectedNetworkAvailable())
1099     {
1100         return CA_STATUS_FAILED;
1101     }
1102
1103 #ifdef ARDUINO
1104     // If max retransmission queue is reached, then don't handle new request
1105     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
1106     {
1107         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
1108         return CA_SEND_FAILED;
1109     }
1110 #endif // ARDUINO
1111
1112     CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
1113     if(!data)
1114     {
1115         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
1116         return CA_MEMORY_ALLOC_FAILED;
1117     }
1118
1119     OIC_LOG_V(INFO_PRIVATE, TAG, "DID of endpoint of this message is %s", endpoint->remoteId);
1120
1121 #ifdef SINGLE_THREAD
1122     CAResult_t result = CAProcessSendData(data);
1123     if (CA_STATUS_OK != result)
1124     {
1125         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1126         OICFree(data);
1127         return result;
1128     }
1129
1130     OICFree(data);
1131
1132 #else
1133 #ifdef WITH_BWT
1134     if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
1135     {
1136         CACheckAndDeleteTimedOutBlockData();
1137         // send block data
1138         CAResult_t res = CASendBlockWiseData(data);
1139         if (CA_NOT_SUPPORTED == res)
1140         {
1141             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1142             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1143             return CA_STATUS_OK;
1144         }
1145         else
1146         {
1147             CADestroyData(data, sizeof(CAData_t));
1148         }
1149
1150         return res;
1151     }
1152     else
1153 #endif // WITH_BWT
1154     {
1155         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1156     }
1157 #endif // SINGLE_THREAD
1158
1159     return CA_STATUS_OK;
1160 }
1161
1162 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1163                              CAErrorCallback errorHandler)
1164 {
1165     g_requestHandler = ReqHandler;
1166     g_responseHandler = RespHandler;
1167     g_errorHandler = errorHandler;
1168 }
1169
1170 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1171 {
1172     g_nwMonitorHandler = nwMonitorHandler;
1173 }
1174
1175 CAResult_t CAInitializeMessageHandler(CATransportAdapter_t transportType)
1176 {
1177     CASetPacketReceivedCallback(CAReceivedPacketCallback);
1178     CASetErrorHandleCallback(CAErrorHandler);
1179
1180 #ifndef SINGLE_THREAD
1181     // create thread pool
1182     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1183     if (CA_STATUS_OK != res)
1184     {
1185         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1186         return res;
1187     }
1188
1189     // send thread initialize
1190     res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1191                                      CASendThreadProcess, CADestroyData);
1192     if (CA_STATUS_OK != res)
1193     {
1194         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1195         return res;
1196     }
1197
1198     // start send thread
1199 #ifndef __TIZENRT__
1200     res = CAQueueingThreadStart(&g_sendThread);
1201 #else
1202     res = CAQueueingThreadStart(&g_sendThread, "IoT_MessageHandlerQueue");
1203 #endif
1204     if (CA_STATUS_OK != res)
1205     {
1206         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1207         return res;
1208     }
1209
1210     // receive thread initialize
1211     res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1212                                      CAReceiveThreadProcess, CADestroyData);
1213     if (CA_STATUS_OK != res)
1214     {
1215         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1216         return res;
1217     }
1218
1219 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1220     // start receive thread
1221     res = CAQueueingThreadStart(&g_receiveThread);
1222     if (CA_STATUS_OK != res)
1223     {
1224         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1225         return res;
1226     }
1227 #endif // SINGLE_HANDLE
1228
1229     // retransmission initialize
1230     res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1231                                      CASendUnicastData, CATimeoutCallback, NULL);
1232     if (CA_STATUS_OK != res)
1233     {
1234         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1235         return res;
1236     }
1237
1238 #ifdef WITH_BWT
1239     // block-wise transfer initialize
1240     res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1241     if (CA_STATUS_OK != res)
1242     {
1243         OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1244         return res;
1245     }
1246 #endif
1247
1248     // start retransmission
1249     res = CARetransmissionStart(&g_retransmissionContext);
1250     if (CA_STATUS_OK != res)
1251     {
1252         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1253         return res;
1254     }
1255
1256     // initialize interface adapters by controller
1257     CAInitializeAdapters(g_threadPoolHandle, transportType);
1258     CASetNetworkMonitorCallbacks(CAAdapterStateChangedCallback, CAConnectionStateChangedCallback);
1259 #else
1260     // retransmission initialize
1261     CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1262                                                 CATimeoutCallback, NULL);
1263     if (CA_STATUS_OK != res)
1264     {
1265         OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1266         return res;
1267     }
1268
1269     CAInitializeAdapters();
1270 #endif // SINGLE_THREAD
1271
1272     return CA_STATUS_OK;
1273 }
1274
1275 static bool CAClearQueueAdapterDataContext(void *data, uint32_t size, void *ctx)
1276 {
1277     (void)size;
1278
1279     if (NULL == data || NULL == ctx)
1280     {
1281         return false;
1282     }
1283
1284     CAData_t *caData = (CAData_t *)data;
1285     CATransportAdapter_t *type = (CATransportAdapter_t *)ctx;
1286
1287     if (NULL != caData && NULL != caData->remoteEndpoint
1288         && caData->remoteEndpoint->adapter == *type)
1289     {
1290         return true;
1291     }
1292     return false;
1293 }
1294
1295 void CAClearMessageHandler(CATransportAdapter_t transportType)
1296 {
1297     CATransportAdapter_t *typeCtx = &transportType;
1298
1299     CAResult_t res = CAQueueingThreadClearContextData(&g_sendThread,
1300                                                       CAClearQueueAdapterDataContext,
1301                                                       typeCtx);
1302
1303     if (res != CA_STATUS_OK)
1304     {
1305         OIC_LOG_V(ERROR, TAG, "Clear send data failed[%d]", res);
1306     }
1307
1308     if (transportType & DEFAULT_RETRANSMISSION_TYPE)
1309     {
1310         res = CARetransmissionClearAdapterData(&g_retransmissionContext, transportType);
1311         if (res != CA_STATUS_OK)
1312         {
1313             OIC_LOG_V(ERROR, TAG, "Clear retransmission data failed[%d]", res);
1314         }
1315     }
1316 }
1317
1318 void CATerminateMessageHandler()
1319 {
1320 #ifndef SINGLE_THREAD
1321     CATransportAdapter_t connType;
1322     u_arraylist_t *list = CAGetSelectedNetworkList();
1323     uint32_t length = u_arraylist_length(list);
1324
1325     uint32_t i = 0;
1326     for (i = 0; i < length; i++)
1327     {
1328         void* ptrType = u_arraylist_get(list, i);
1329
1330         if (NULL == ptrType)
1331         {
1332             continue;
1333         }
1334
1335         connType = *(CATransportAdapter_t *)ptrType;
1336         CAStopAdapter(connType);
1337     }
1338
1339     // stop retransmission
1340     if (NULL != g_retransmissionContext.threadMutex)
1341     {
1342         CARetransmissionStop(&g_retransmissionContext);
1343     }
1344
1345     // stop thread
1346     // delete thread data
1347     if (NULL != g_sendThread.threadMutex)
1348     {
1349         CAQueueingThreadStop(&g_sendThread);
1350     }
1351
1352     // stop thread
1353     // delete thread data
1354     if (NULL != g_receiveThread.threadMutex)
1355     {
1356 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1357         CAQueueingThreadStop(&g_receiveThread);
1358 #endif
1359     }
1360
1361     // destroy thread pool
1362     if (NULL != g_threadPoolHandle)
1363     {
1364         ca_thread_pool_free(g_threadPoolHandle);
1365         g_threadPoolHandle = NULL;
1366     }
1367
1368 #ifdef WITH_BWT
1369     CATerminateBlockWiseTransfer();
1370 #endif
1371     CARetransmissionDestroy(&g_retransmissionContext);
1372     CAQueueingThreadDestroy(&g_sendThread);
1373     CAQueueingThreadDestroy(&g_receiveThread);
1374
1375     // terminate interface adapters by controller
1376     CATerminateAdapters();
1377 #else
1378     // terminate interface adapters by controller
1379     CATerminateAdapters();
1380
1381     // stop retransmission
1382     CARetransmissionStop(&g_retransmissionContext);
1383     CARetransmissionDestroy(&g_retransmissionContext);
1384 #endif // SINGLE_THREAD
1385 }
1386
1387 static void CALogPayloadInfo(CAInfo_t *info)
1388 {
1389     if (info)
1390     {
1391         if (info->options)
1392         {
1393             for (uint32_t i = 0; i < info->numOptions; i++)
1394             {
1395                 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1396
1397                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1398             }
1399         }
1400
1401         if (info->payload)
1402         {
1403             OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1404                       info->payloadSize);
1405         }
1406
1407         if (info->token)
1408         {
1409             OIC_LOG(DEBUG, TAG, "token:");
1410             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1411                            info->tokenLength);
1412         }
1413         OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1414     }
1415     else
1416     {
1417         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1418     }
1419 }
1420
1421 void CAErrorHandler(const CAEndpoint_t *endpoint,
1422                     const void *data, uint32_t dataLen,
1423                     CAResult_t result)
1424 {
1425     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1426     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1427     VERIFY_NON_NULL_VOID(data, TAG, "data");
1428
1429     if (0 == dataLen)
1430     {
1431         OIC_LOG(ERROR, TAG, "dataLen is zero");
1432         return;
1433     }
1434
1435 #ifndef SINGLE_THREAD
1436     uint32_t code = CA_NOT_FOUND;
1437     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1438     //Get PDU data
1439     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1440     if (NULL == pdu)
1441     {
1442         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1443         return;
1444     }
1445
1446     CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1447     if (!cadata)
1448     {
1449         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1450         coap_delete_pdu(pdu);
1451         return;
1452     }
1453
1454     cadata->errorInfo->result = result;
1455
1456     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1457     coap_delete_pdu(pdu);
1458 #else
1459     (void)result;
1460 #endif
1461
1462     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1463     return;
1464 }
1465
1466 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1467 {
1468     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1469 #ifndef SINGLE_THREAD
1470     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1471     if (!cadata)
1472     {
1473         OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1474         return;
1475     }
1476
1477     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1478     if (!ep)
1479     {
1480         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1481         OICFree(cadata);
1482         return;
1483     }
1484
1485     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1486     if (!errorInfo)
1487     {
1488         OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1489         OICFree(cadata);
1490         CAFreeEndpoint(ep);
1491         return;
1492     }
1493
1494     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1495     if (CA_STATUS_OK != res)
1496     {
1497         OIC_LOG(ERROR, TAG, "info clone failed");
1498         OICFree(cadata);
1499         OICFree(errorInfo);
1500         CAFreeEndpoint(ep);
1501         return;
1502     }
1503
1504     errorInfo->result = result;
1505     cadata->remoteEndpoint = ep;
1506     cadata->errorInfo = errorInfo;
1507     cadata->dataType = CA_ERROR_DATA;
1508
1509     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1510 #endif
1511     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1512 }
1513
1514
1515
1516 #ifndef ARDUINO
1517 #ifdef __TIZENRT__
1518 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1519 {
1520
1521         if(data == NULL || pdu == NULL)
1522         {
1523                 printf("INVALID INPUT, CALogPDUInfo FAIL\n");
1524         }
1525
1526         char type[30] = "";
1527
1528         switch(data->dataType)
1529         {
1530                 case CA_REQUEST_DATA:
1531                         strncpy(type, "\e[32mREQUEST  <<<<\e[m", 30);
1532                         break;
1533                 case CA_RESPONSE_DATA:
1534                         strncpy(type, "\e[36mRESPONSE >>>>\e[m", 30);
1535                         break;
1536                 case CA_ERROR_DATA:
1537                         strncpy(type, "ERROR", 30);
1538                         break;
1539                 case CA_RESPONSE_FOR_RES:
1540                         strncpy(type, "RESP_RES >>>>", 30);
1541                         break;
1542                 default:
1543                         snprintf(type, 30, "Type : %d", data->dataType);
1544                         break;
1545         }
1546
1547
1548         char method[20] = "";
1549         const CAInfo_t *info = NULL;
1550         if (NULL != data->requestInfo)
1551         {
1552                 switch(data->requestInfo->method)
1553                 {
1554                         case CA_GET:
1555                                 strncpy(method, "GET", 20);
1556                                 break;
1557                         case CA_POST:
1558                                 strncpy(method, "POST", 20);
1559                                 break;
1560                         case CA_PUT:
1561                                 strncpy(method, "PUT", 20);
1562                                 break;
1563                         case CA_DELETE:
1564                                 strncpy(method, "DEL", 20);
1565                                 break;
1566                         default:
1567                                 sprintf(method, "Method : %d", data->requestInfo->method);
1568                                 break;
1569                 }
1570                 info = &data->requestInfo->info;
1571         }
1572
1573         if(NULL != data->responseInfo)
1574         {
1575
1576                 sprintf(method, "result : %d", data->responseInfo->result);
1577                 info = &data->responseInfo->info;
1578         }
1579
1580
1581         char log_buffer[1024] = "";
1582         sprintf(log_buffer, "CA_LOG [%5d] | %-13s | %-12s | msg size : %4d | %s", pdu->transport_hdr->udp.id , type, method, pdu->length, info->resourceUri);
1583
1584         puts(log_buffer);
1585 }
1586
1587
1588 #else
1589
1590 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1591 {
1592     OIC_LOG(DEBUG, TAG, "CALogPDUInfo");
1593
1594     VERIFY_NON_NULL_VOID(data, TAG, "data");
1595     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1596     OIC_TRACE_BEGIN(%s:CALogPDUInfo, TAG);
1597
1598     OIC_LOG(INFO, ANALYZER_TAG, "=================================================");
1599     if(SEND_TYPE_MULTICAST == data->type)
1600     {
1601         OIC_LOG(INFO, ANALYZER_TAG, "Is Multicast = true");
1602     }
1603     else
1604     {
1605         OIC_LOG(INFO, ANALYZER_TAG, "Is Multicast = false");
1606     }
1607
1608     if (NULL != data->remoteEndpoint)
1609     {
1610         CALogAdapterTypeInfo(data->remoteEndpoint->adapter);
1611         OIC_LOG_V(INFO, ANALYZER_TAG, "Address = [%s]:[%d]", data->remoteEndpoint->addr,
1612                   data->remoteEndpoint->port);
1613     }
1614
1615     switch(data->dataType)
1616     {
1617         case CA_REQUEST_DATA:
1618             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_REQUEST_DATA]");
1619             break;
1620         case CA_RESPONSE_DATA:
1621             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_RESPONSE_DATA]");
1622             break;
1623         case CA_ERROR_DATA:
1624             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_ERROR_DATA]");
1625             break;
1626         case CA_RESPONSE_FOR_RES:
1627             OIC_LOG(INFO, ANALYZER_TAG, "Data Type = [CA_RESPONSE_FOR_RES]");
1628             break;
1629         default:
1630             OIC_LOG_V(INFO, ANALYZER_TAG, "Data Type = [%d]", data->dataType);
1631             break;
1632     }
1633
1634     const CAInfo_t *info = NULL;
1635     if (NULL != data->requestInfo)
1636     {
1637         switch(data->requestInfo->method)
1638         {
1639             case CA_GET:
1640                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [GET]");
1641                 break;
1642             case CA_POST:
1643                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [POST]");
1644                 break;
1645             case CA_PUT:
1646                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [PUT]");
1647                 break;
1648             case CA_DELETE:
1649                 OIC_LOG(INFO, ANALYZER_TAG, "Method = [DELETE]");
1650                 break;
1651             default:
1652                 OIC_LOG_V(INFO, ANALYZER_TAG, "Method = [%d]", data->requestInfo->method);
1653                 break;
1654         }
1655         info = &data->requestInfo->info;
1656     }
1657
1658     if (NULL != data->responseInfo)
1659     {
1660         OIC_LOG_V(INFO, ANALYZER_TAG, "result code = [%d]", data->responseInfo->result);
1661         info = &data->responseInfo->info;
1662     }
1663
1664     if (pdu->transport_hdr)
1665     {
1666         OIC_LOG_V(INFO, ANALYZER_TAG, "Msg ID = [%d]", pdu->transport_hdr->udp.id);
1667     }
1668
1669     if (info)
1670     {
1671         OIC_LOG(INFO, ANALYZER_TAG, "Coap Token");
1672         OIC_LOG_BUFFER(INFO, ANALYZER_TAG, (const uint8_t *) info->token, info->tokenLength);
1673         OIC_TRACE_BUFFER("OIC_CA_MSG_HANDLE:CALogPDUInfo:token",
1674                          (const uint8_t *) info->token, info->tokenLength);
1675         OIC_LOG_V(INFO, ANALYZER_TAG, "Res URI = [%s]", info->resourceUri);
1676         OIC_TRACE_MARK(%s:CALogPDUInfo:uri:%s, TAG, info->resourceUri);
1677
1678         if (CA_FORMAT_APPLICATION_CBOR == info->payloadFormat)
1679         {
1680             OIC_LOG(INFO, ANALYZER_TAG, "Payload Format = [CA_FORMAT_APPLICATION_CBOR]");
1681         }
1682         else
1683         {
1684             OIC_LOG_V(INFO, ANALYZER_TAG, "Payload Format = [%d]", info->payloadFormat);
1685         }
1686     }
1687
1688     size_t payloadLen = (pdu->data) ? (unsigned char *) pdu->hdr + pdu->length - pdu->data : 0;
1689     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Message Full Size = [%u]", pdu->length);
1690     OIC_LOG(INFO, ANALYZER_TAG, "CoAP Header (+ 0xFF)");
1691     OIC_LOG_BUFFER(INFO, ANALYZER_TAG,  (const uint8_t *) pdu->transport_hdr,
1692                    pdu->length - payloadLen);
1693     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Header size = [%" PRIuPTR "]", (size_t) pdu->length - payloadLen);
1694
1695     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Payload");
1696     OIC_LOG_BUFFER(INFO_PRIVATE, ANALYZER_TAG, pdu->data, payloadLen);
1697     OIC_LOG_V(INFO, ANALYZER_TAG, "CoAP Payload Size = [%" PRIuPTR "]", payloadLen);
1698     OIC_LOG(INFO, ANALYZER_TAG, "=================================================");
1699
1700     // samsung log
1701     CASamsungLogMessage(data, pdu);
1702     OIC_TRACE_END();
1703 }
1704
1705 static void CASamsungLogMessage(const CAData_t *data, const coap_pdu_t *pdu)
1706 {
1707     OIC_LOG(INFO, TAG, "CASamsungLogMessage");
1708     VERIFY_NON_NULL_VOID(data, TAG, "data");
1709     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1710     VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "data->remoteEndpoint");
1711
1712     const CAInfo_t *info = NULL;
1713     if (NULL != data->requestInfo)
1714     {
1715         info = &data->requestInfo->info;
1716     }
1717
1718     if (NULL != data->responseInfo)
1719     {
1720         info = &data->responseInfo->info;
1721     }
1722
1723     VERIFY_NON_NULL_VOID(info, TAG, "info");
1724
1725     memset(g_headerBuffer, 0, MAX_LOG_BUFFER_SIZE);
1726     g_headerIndex = 0;
1727
1728     g_headerBuffer[g_headerIndex++] = data->dataType;
1729     g_headerBuffer[g_headerIndex++] = '|';
1730     g_headerBuffer[g_headerIndex++] = data->remoteEndpoint->adapter;
1731     g_headerBuffer[g_headerIndex++] = '|';
1732     g_headerBuffer[g_headerIndex++] = data->type;
1733     g_headerBuffer[g_headerIndex++] = '|';
1734
1735     if (NULL != data->remoteEndpoint)
1736     {
1737         int i = 0;
1738         while (data->remoteEndpoint->addr[i])
1739         {
1740             g_headerBuffer[g_headerIndex++] = data->remoteEndpoint->addr[i];
1741             i++;
1742         }
1743         g_headerBuffer[g_headerIndex++] = ':';
1744         g_headerBuffer[g_headerIndex++] = (data->remoteEndpoint->port >> 8) & 0x0000ff;
1745         g_headerBuffer[g_headerIndex++] = data->remoteEndpoint->port & 0x000000ff;
1746     }
1747
1748     g_headerBuffer[g_headerIndex++] = '|';
1749     if (data->requestInfo)
1750     {
1751         g_headerBuffer[g_headerIndex++] = data->requestInfo->method;
1752     }
1753     else
1754     {
1755         g_headerBuffer[g_headerIndex++] = 0;
1756     }
1757
1758     g_headerBuffer[g_headerIndex++] = '|';
1759     if (data->responseInfo)
1760     {
1761         g_headerBuffer[g_headerIndex++] = data->responseInfo->result;
1762     }
1763     else
1764     {
1765         g_headerBuffer[g_headerIndex++] = 0;
1766     }
1767     g_headerBuffer[g_headerIndex++] = '|';
1768
1769     if (pdu->transport_hdr)
1770     {
1771         g_headerBuffer[g_headerIndex++] = (pdu->transport_hdr->udp.id >> 8) & 0x0000ff;
1772         g_headerBuffer[g_headerIndex++] = pdu->transport_hdr->udp.id & 0x000000ff;
1773     }
1774     else
1775     {
1776         g_headerBuffer[g_headerIndex++] = 0;
1777         g_headerBuffer[g_headerIndex++] = 0;
1778     }
1779     g_headerBuffer[g_headerIndex++] = '|';
1780
1781     if (info->token && info->tokenLength > 0)
1782     {
1783         for (size_t i = 0; i < info->tokenLength; i++)
1784         {
1785             g_headerBuffer[g_headerIndex++] = info->token[i];
1786         }
1787         g_headerBuffer[g_headerIndex++] = '|';
1788     }
1789
1790     if (info->resourceUri)
1791     {
1792         size_t i = 0;
1793         while (info->resourceUri[i])
1794         {
1795             g_headerBuffer[g_headerIndex++] = info->resourceUri[i];
1796             i++;
1797         }
1798         g_headerBuffer[g_headerIndex++] = '|';
1799     }
1800
1801     OIC_LOG_CA_BUFFER(INFO, TAG, (uint8_t *) g_headerBuffer, g_headerIndex, 1);
1802     size_t payloadLen = (unsigned char *) pdu->hdr + pdu->length - pdu->data;
1803     OIC_LOG_CA_BUFFER(INFO_PRIVATE, TAG, pdu->data, payloadLen, 0);
1804 }
1805 #endif
1806
1807 #else
1808 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1809 {
1810     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1811     (void)data;
1812
1813     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1814     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->transport_hdr->udp.type);
1815     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->transport_hdr->udp.code);
1816     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1817     OIC_LOG_BUFFER(DEBUG, TAG, pdu->transport_hdr->udp.token,
1818                    pdu->transport_hdr->udp.token_length);
1819 }
1820 #endif