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