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