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