Fixed a large amount of memory leaks/ Null pointer dereferences
[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 "config.h" /* for coap protocol */
32 #include "oic_malloc.h"
33 #include "canetworkconfigurator.h"
34 #include "caadapterutils.h"
35 #include "cainterfacecontroller.h"
36 #include "caretransmission.h"
37
38 #ifdef WITH_BWT
39 #include "cablockwisetransfer.h"
40 #endif
41
42 #ifndef  SINGLE_THREAD
43 #include "uqueue.h"
44 #include "cathreadpool.h" /* for thread pool */
45 #include "caqueueingthread.h"
46
47 #define SINGLE_HANDLE
48 #define MAX_THREAD_POOL_SIZE    20
49
50 // thread pool handle
51 static ca_thread_pool_t g_threadPoolHandle = NULL;
52
53 // message handler main thread
54 static CAQueueingThread_t g_sendThread;
55 static CAQueueingThread_t g_receiveThread;
56
57 #else
58 #define CA_MAX_RT_ARRAY_SIZE    3
59 #endif  /* SINGLE_THREAD */
60
61 #define TAG "CA_MSG_HNDLR"
62
63 static CARetransmission_t g_retransmissionContext;
64
65 // handler field
66 static CARequestCallback g_requestHandler = NULL;
67 static CAResponseCallback g_responseHandler = NULL;
68 static CAErrorCallback g_errorHandler = NULL;
69
70 static void CAErrorHandler(const CAEndpoint_t *endpoint,
71                            const void *data, uint32_t dataLen,
72                            CAResult_t result);
73
74 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void *data,
75                                        CADataType_t dataType);
76
77 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
78                             CAResult_t result);
79
80 #ifdef SINGLE_THREAD
81 static void CAProcessReceivedData(CAData_t *data);
82 #endif
83 static void CADestroyData(void *data, uint32_t size);
84 static void CALogPayloadInfo(CAInfo_t *info);
85 static bool CADropSecondRequest(const CAEndpoint_t *endpoint, uint16_t messageId);
86
87 #ifdef WITH_BWT
88 void CAAddDataToSendThread(CAData_t *data)
89 {
90     OIC_LOG(DEBUG, TAG, "IN");
91     VERIFY_NON_NULL_VOID(data, TAG, "data");
92
93     // add thread
94     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
95
96     OIC_LOG(DEBUG, TAG, "OUT");
97 }
98
99 void CAAddDataToReceiveThread(CAData_t *data)
100 {
101     OIC_LOG(DEBUG, TAG, "IN - CAAddDataToReceiveThread");
102     VERIFY_NON_NULL_VOID(data, TAG, "data");
103
104     // add thread
105     CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
106
107     OIC_LOG(DEBUG, TAG, "OUT - CAAddDataToReceiveThread");
108 }
109 #endif
110
111 static bool CAIsSelectedNetworkAvailable()
112 {
113     u_arraylist_t *list = CAGetSelectedNetworkList();
114     if (!list || list->length == 0)
115     {
116         OIC_LOG(ERROR, TAG, "No selected network");
117         return false;
118     }
119
120     return true;
121 }
122
123 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint, const void *data, CADataType_t dataType)
124 {
125     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
126     CAInfo_t *info = NULL;
127     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
128     if (!cadata)
129     {
130         OIC_LOG(ERROR, TAG, "memory allocation failed");
131         return NULL;
132     }
133
134     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
135     if (!ep)
136     {
137         OIC_LOG(ERROR, TAG, "endpoint clone failed");
138         OICFree(cadata);
139         return NULL;
140     }
141
142     OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
143     CAResult_t result;
144
145     if(CA_RESPONSE_DATA == dataType)
146     {
147         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
148         if (!resInfo)
149         {
150             OIC_LOG(ERROR, TAG, "memory allocation failed");
151             OICFree(cadata);
152             CAFreeEndpoint(ep);
153             return NULL;
154         }
155
156         result = CAGetResponseInfoFromPDU(data, resInfo);
157         if (CA_STATUS_OK != result)
158         {
159             OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
160             CAFreeEndpoint(ep);
161             CADestroyResponseInfoInternal(resInfo);
162             OICFree(cadata);
163             return NULL;
164         }
165         cadata->responseInfo = resInfo;
166         info = &resInfo->info;
167         OIC_LOG(DEBUG, TAG, "Response Info :");
168         CALogPayloadInfo(info);
169     }
170     else if (CA_REQUEST_DATA == dataType)
171     {
172         CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
173         if (!reqInfo)
174         {
175             OIC_LOG(ERROR, TAG, "memory allocation failed");
176             OICFree(cadata);
177             CAFreeEndpoint(ep);
178             return NULL;
179         }
180
181         result = CAGetRequestInfoFromPDU(data, reqInfo);
182         if (CA_STATUS_OK != result)
183         {
184             OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
185             CAFreeEndpoint(ep);
186             CADestroyRequestInfoInternal(reqInfo);
187             OICFree(cadata);
188             return NULL;
189         }
190
191         if (CADropSecondRequest(endpoint, reqInfo->info.messageId))
192         {
193             OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
194             CAFreeEndpoint(ep);
195             CADestroyRequestInfoInternal(reqInfo);
196             OICFree(cadata);
197             return NULL;
198         }
199
200         cadata->requestInfo = reqInfo;
201         info = &reqInfo->info;
202         OIC_LOG(DEBUG, TAG, "Request Info :");
203         CALogPayloadInfo(info);
204    }
205     else if (CA_ERROR_DATA == dataType)
206     {
207         CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
208         if (!errorInfo)
209         {
210             OIC_LOG(ERROR, TAG, "Memory allocation failed!");
211             OICFree(cadata);
212             CAFreeEndpoint(ep);
213             return NULL;
214         }
215
216         CAResult_t result = CAGetErrorInfoFromPDU(data, errorInfo);
217         if (CA_STATUS_OK != result)
218         {
219             OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
220             CAFreeEndpoint(ep);
221             OICFree(errorInfo);
222             OICFree(cadata);
223             return NULL;
224         }
225
226         cadata->errorInfo = errorInfo;
227         info = &errorInfo->info;
228         OIC_LOG(DEBUG, TAG, "error Info :");
229         CALogPayloadInfo(info);
230     }
231
232     cadata->remoteEndpoint = ep;
233     cadata->dataType = dataType;
234
235     return cadata;
236
237     OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
238 }
239
240 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
241 {
242     OIC_LOG(DEBUG, TAG, "IN");
243     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
244     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
245
246     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
247     if (!ep)
248     {
249         OIC_LOG(ERROR, TAG, "clone failed");
250         return;
251     }
252
253     CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
254
255     if (!resInfo)
256     {
257         OIC_LOG(ERROR, TAG, "calloc failed");
258         CAFreeEndpoint(ep);
259         return;
260     }
261
262     resInfo->result = CA_RETRANSMIT_TIMEOUT;
263     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
264     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
265
266     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info));
267     if (CA_STATUS_OK != res)
268     {
269         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
270         CADestroyResponseInfoInternal(resInfo);
271         CAFreeEndpoint(ep);
272         return;
273     }
274
275     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
276     if (NULL == cadata)
277     {
278         OIC_LOG(ERROR, TAG, "memory allocation failed !");
279         CAFreeEndpoint(ep);
280         CADestroyResponseInfoInternal(resInfo);
281         return;
282     }
283
284     cadata->type = SEND_TYPE_UNICAST;
285     cadata->remoteEndpoint = ep;
286     cadata->requestInfo = NULL;
287     cadata->responseInfo = resInfo;
288
289 #ifdef SINGLE_THREAD
290     CAProcessReceivedData(cadata);
291 #else
292     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
293 #endif
294
295     OIC_LOG(DEBUG, TAG, "OUT");
296 }
297
298 static void CADestroyData(void *data, uint32_t size)
299 {
300     OIC_LOG(DEBUG, TAG, "CADestroyData IN");
301     CAData_t *cadata = (CAData_t *) data;
302
303     if (NULL == cadata)
304     {
305         OIC_LOG(ERROR, TAG, "cadata is NULL");
306         return;
307     }
308
309     if (NULL != cadata->remoteEndpoint)
310     {
311         CAFreeEndpoint(cadata->remoteEndpoint);
312     }
313
314     if (NULL != cadata->requestInfo)
315     {
316         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
317     }
318
319     if (NULL != cadata->responseInfo)
320     {
321         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
322     }
323
324     if (NULL != cadata->errorInfo)
325     {
326         CADestroyErrorInfoInternal(cadata->errorInfo);
327     }
328
329     OICFree(cadata->options);
330     OICFree(cadata);
331     OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
332 }
333
334 #ifdef SINGLE_THREAD
335 static void CAProcessReceivedData(CAData_t *data)
336 {
337     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
338     if (!data)
339     {
340         OIC_LOG(ERROR, TAG, "thread data error!!");
341         return;
342     }
343
344     // parse the data and call the callbacks.
345     // #1 parse the data
346     // #2 get endpoint
347     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
348     if (!rep)
349     {
350         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
351         return;
352     }
353
354     if (data->requestInfo && g_requestHandler)
355     {
356         g_requestHandler(rep, data->requestInfo);
357     }
358     else if (data->responseInfo && g_responseHandler)
359     {
360         g_responseHandler(rep, data->responseInfo);
361     }
362     else if (data->errorInfo && g_errorHandler)
363     {
364         g_errorHandler(rep, data->errorInfo);
365     }
366
367 #ifdef SINGLE_THREAD
368     CADestroyData(data, sizeof(CAData_t));
369 #endif
370
371     OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
372 }
373 #endif
374
375 #ifndef SINGLE_THREAD
376
377 static void CAReceiveThreadProcess(void *threadData)
378 {
379     OIC_LOG(DEBUG, TAG, "IN");
380 #ifndef SINGLE_HANDLE
381     CAData_t *data = (CAData_t *) threadData;
382     CAProcessReceivedData(data);
383 #endif
384     OIC_LOG(DEBUG, TAG, "OUT");
385 }
386 #endif
387
388 static CAResult_t CAProcessSendData(const CAData_t *data)
389 {
390     OIC_LOG(DEBUG, TAG, "IN");
391     VERIFY_NON_NULL(data, TAG, "data");
392     VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
393
394     CAResult_t res = CA_STATUS_FAILED;
395
396     CASendDataType_t type = data->type;
397
398     coap_pdu_t *pdu = NULL;
399     CAInfo_t *info = NULL;
400
401     if (SEND_TYPE_UNICAST == type)
402     {
403
404         OIC_LOG(DEBUG,TAG,"Unicast message");
405         if (NULL != data->requestInfo)
406         {
407             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
408
409             info = &data->requestInfo->info;
410             pdu = CAGeneratePDU(data->requestInfo->method, info);
411         }
412         else if (NULL != data->responseInfo)
413         {
414             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
415
416             info = &data->responseInfo->info;
417             pdu = CAGeneratePDU(data->responseInfo->result, info);
418         }
419         else
420         {
421             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
422             return CA_STATUS_INVALID_PARAM;
423         }
424
425         // interface controller function call.
426         if (NULL != pdu)
427         {
428 #ifdef WITH_BWT
429             if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter)
430             {
431                 // Blockwise transfer
432                 if (NULL != info)
433                 {
434                     CAResult_t res = CAAddBlockOption(&pdu, *info,
435                                                       data->remoteEndpoint);
436                     if (CA_STATUS_OK != res)
437                     {
438                         OIC_LOG(INFO, TAG, "to write block option has failed");
439                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
440                         coap_delete_pdu(pdu);
441                         return res;
442                     }
443                 }
444             }
445 #endif
446             CALogPDUInfo(pdu);
447
448             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
449             if (CA_STATUS_OK != res)
450             {
451                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
452                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
453                 coap_delete_pdu(pdu);
454                 return res;
455             }
456             // for retransmission
457             res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
458                                            pdu->length);
459             if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
460             {
461                 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
462                 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
463                 coap_delete_pdu(pdu);
464                 return res;
465             }
466
467             coap_delete_pdu(pdu);
468         }
469         else
470         {
471             OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
472             CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
473             return CA_SEND_FAILED;
474         }
475     }
476     else if (SEND_TYPE_MULTICAST == type)
477     {
478         OIC_LOG(DEBUG,TAG,"Multicast message");
479         if (NULL != data->requestInfo)
480         {
481             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
482
483             info = &data->requestInfo->info;
484             pdu = CAGeneratePDU(CA_GET, info);
485             if (NULL != pdu)
486             {
487 #ifdef WITH_BWT
488                 if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter)
489                 {
490                     // Blockwise transfer
491                     CAResult_t res = CAAddBlockOption(&pdu, data->requestInfo->info,
492                                                       data->remoteEndpoint);
493                     if (CA_STATUS_OK != res)
494                     {
495                         OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
496                         CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
497                         coap_delete_pdu(pdu);
498                         return res;
499                     }
500                 }
501 #endif
502                 CALogPDUInfo(pdu);
503
504                 res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
505                 if (CA_STATUS_OK != res)
506                 {
507                     OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
508                     CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
509                     coap_delete_pdu(pdu);
510                     return res;
511                 }
512
513                 coap_delete_pdu(pdu);
514             }
515             else
516             {
517                 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
518                 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
519                 return CA_SEND_FAILED;
520             }
521         }
522         else
523         {
524             OIC_LOG(ERROR, TAG, "request info is empty");
525             return CA_SEND_FAILED;
526         }
527     }
528
529     OIC_LOG(DEBUG, TAG, "OUT");
530     return CA_STATUS_OK;
531 }
532
533 #ifndef SINGLE_THREAD
534 static void CASendThreadProcess(void *threadData)
535 {
536     CAData_t *data = (CAData_t *) threadData;
537     CAProcessSendData(data);
538 }
539
540 #endif
541
542 /*
543  * If a second message arrives with the same token and the other address
544  * family, drop it.  Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
545  * This can be made more robust (for instance, another message could arrive
546  * in between), but it is good enough for now.
547  */
548 static bool CADropSecondRequest(const CAEndpoint_t *endpoint, uint16_t messageId)
549 {
550     if (!endpoint)
551     {
552         return true;
553     }
554     if (endpoint->adapter != CA_ADAPTER_IP)
555     {
556         return false;
557     }
558
559     bool ret = false;
560     CATransportFlags_t familyFlags = endpoint->flags & CA_IPFAMILY_MASK;
561
562     if (messageId == caglobals.ca.previousRequestMessageId)
563     {
564         if ((familyFlags ^ caglobals.ca.previousRequestFlags) == CA_IPFAMILY_MASK)
565         {
566             if (familyFlags & CA_IPV6)
567             {
568                 OIC_LOG(INFO, TAG, "IPv6 duplicate response ignored");
569             }
570             else
571             {
572                 OIC_LOG(INFO, TAG, "IPv4 duplicate response ignored");
573             }
574             ret = true;
575         }
576     }
577     caglobals.ca.previousRequestFlags = familyFlags;
578     caglobals.ca.previousRequestMessageId = messageId;
579     return ret;
580 }
581
582 static void CAReceivedPacketCallback(const CAEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLen)
583 {
584     OIC_LOG(DEBUG, TAG, "IN");
585     VERIFY_NON_NULL_VOID(remoteEndpoint, TAG, "remoteEndpoint");
586     VERIFY_NON_NULL_VOID(data, TAG, "data");
587
588     uint32_t code = CA_NOT_FOUND;
589     CAData_t *cadata = NULL;
590
591     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
592     if (NULL == pdu)
593     {
594         OIC_LOG(ERROR, TAG, "Parse PDU failed");
595         return;
596     }
597
598     OIC_LOG_V(DEBUG, TAG, "code = %d", code);
599     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
600     {
601         cadata = CAGenerateHandlerData(remoteEndpoint, pdu, CA_REQUEST_DATA);
602         if (!cadata)
603         {
604             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
605             coap_delete_pdu(pdu);
606             return;
607         }
608     }
609     else
610     {
611         cadata = CAGenerateHandlerData(remoteEndpoint, pdu, CA_RESPONSE_DATA);
612         if (!cadata)
613         {
614             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
615             coap_delete_pdu(pdu);
616             return;
617         }
618
619         // for retransmission
620         void *retransmissionPdu = NULL;
621         CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
622                                      pdu->length, &retransmissionPdu);
623
624         // get token from saved data in retransmission list
625         if (retransmissionPdu && CA_EMPTY == code)
626         {
627             if (cadata->responseInfo)
628             {
629                 CAInfo_t *info = &cadata->responseInfo->info;
630                 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
631                                                    info);
632                 if (CA_STATUS_OK != res)
633                 {
634                     OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
635                     OICFree(info->token);
636                     info->tokenLength = 0;
637                 }
638             }
639         }
640         OICFree(retransmissionPdu);
641     }
642
643     cadata->type = SEND_TYPE_UNICAST;
644
645 #ifdef SINGLE_THREAD
646     CAProcessReceivedData(cadata);
647 #else
648 #ifdef WITH_BWT
649         if (CA_ADAPTER_GATT_BTLE != remoteEndpoint->adapter)
650         {
651             CAResult_t res = CAReceiveBlockWiseData(pdu, remoteEndpoint, cadata, dataLen);
652             if (CA_NOT_SUPPORTED == res)
653             {
654                 OIC_LOG(ERROR, TAG, "this message does not have block option");
655                 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
656             }
657             else
658             {
659                 CADestroyData(cadata, sizeof(CAData_t));
660             }
661         }
662         else
663 #endif
664         {
665             CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
666         }
667 #endif
668
669     coap_delete_pdu(pdu);
670
671     OIC_LOG(DEBUG, TAG, "OUT");
672 }
673
674 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
675 {
676     OIC_LOG(DEBUG, TAG, "IN");
677
678     OIC_LOG(DEBUG, TAG, "OUT");
679 }
680
681 void CAHandleRequestResponseCallbacks()
682 {
683 #ifdef SINGLE_THREAD
684     CAReadData();
685     CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
686 #else
687 #ifdef SINGLE_HANDLE
688     // parse the data and call the callbacks.
689     // #1 parse the data
690     // #2 get endpoint
691
692     ca_mutex_lock(g_receiveThread.threadMutex);
693
694     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
695
696     ca_mutex_unlock(g_receiveThread.threadMutex);
697
698     if (NULL == item)
699     {
700         return;
701     }
702
703     // get values
704     void *msg = item->msg;
705
706     if (NULL == msg)
707     {
708         return;
709     }
710
711     // get endpoint
712     CAData_t *td = (CAData_t *) msg;
713
714     if (td->requestInfo && g_requestHandler)
715     {
716         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
717         g_requestHandler(td->remoteEndpoint, td->requestInfo);
718     }
719     else if (td->responseInfo && g_responseHandler)
720     {
721         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
722         g_responseHandler(td->remoteEndpoint, td->responseInfo);
723     }
724     else if (td->errorInfo && g_errorHandler)
725     {
726         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
727         g_errorHandler(td->remoteEndpoint, td->errorInfo);
728     }
729
730     CADestroyData(msg, sizeof(CAData_t));
731     OICFree(item);
732
733 #endif /* SINGLE_HANDLE */
734 #endif
735 }
736
737 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
738                                    CADataType_t dataType)
739 {
740     OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
741     CAInfo_t *info = NULL;
742
743     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
744     if (!cadata)
745     {
746         OIC_LOG(ERROR, TAG, "memory allocation failed");
747         return NULL;
748     }
749
750     if(CA_REQUEST_DATA == dataType)
751     {
752         // clone request info
753         CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
754
755         if(!request)
756         {
757             OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
758             OICFree(cadata);
759             return NULL;
760         }
761
762         cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
763         info = &request->info;
764         cadata->requestInfo =  request;
765     }
766     else if(CA_RESPONSE_DATA == dataType)
767     {
768         // clone response info
769         CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
770
771         if(!response)
772         {
773             OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
774             OICFree(cadata);
775             return NULL;
776         }
777
778         cadata->type = SEND_TYPE_UNICAST;
779         info = &response->info;
780         cadata->responseInfo = response;
781     }
782     else
783     {
784         OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
785         OICFree(cadata);
786         return NULL;
787     }
788
789     if (NULL != info->options && 0 < info->numOptions)
790     {
791         uint8_t numOptions = info->numOptions;
792         // copy data
793         CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
794                                                                         * numOptions);
795         if(!headerOption)
796         {
797             OIC_LOG(ERROR, TAG, "memory allocation failed");
798             CADestroyData(cadata, sizeof(CAData_t));
799             return NULL;
800         }
801
802         memcpy(headerOption, info->options, sizeof(CAHeaderOption_t) * numOptions);
803
804         cadata->options = headerOption;
805         cadata->numOptions = numOptions;
806     }
807
808     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
809     if (!ep)
810     {
811         OIC_LOG(ERROR, TAG, "endpoint clone failed");
812         CADestroyData(cadata, sizeof(CAData_t));
813         return NULL;
814     }
815
816     cadata->remoteEndpoint = ep;
817     cadata->dataType = dataType;
818     return cadata;
819 }
820
821 CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
822 {
823     OIC_LOG(DEBUG, TAG, "IN");
824
825     VERIFY_NON_NULL(object, TAG, "object");
826     VERIFY_NON_NULL(request, TAG, "request");
827
828     if (false == CAIsSelectedNetworkAvailable())
829     {
830         return CA_STATUS_FAILED;
831     }
832
833 #ifdef ARDUINO
834     // If max retransmission queue is reached, then don't handle new request
835     if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
836     {
837         OIC_LOG(ERROR, TAG, "max RT queue size reached!");
838         return CA_SEND_FAILED;
839     }
840 #endif /* ARDUINO */
841
842     CAData_t *data = CAPrepareSendData(object, request, CA_REQUEST_DATA);
843     if(!data)
844     {
845         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
846         return CA_MEMORY_ALLOC_FAILED;
847     }
848
849 #ifdef SINGLE_THREAD
850     CAResult_t result = CAProcessSendData(data);
851     if(CA_STATUS_OK != result)
852     {
853         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
854         return result;
855     }
856
857     CADestroyData(data, sizeof(CAData_t));
858 #else
859 #ifdef WITH_BWT
860     if (CA_ADAPTER_GATT_BTLE != object->adapter)
861     {
862         // send block data
863         CAResult_t res = CASendBlockWiseData(data);
864         if(CA_NOT_SUPPORTED == res)
865         {
866             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
867             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
868             return CA_STATUS_OK;
869         }
870         else
871         {
872             CADestroyData(data, sizeof(CAData_t));
873         }
874         return res;
875     }
876     else
877 #endif
878     {
879         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
880     }
881 #endif
882
883     OIC_LOG(DEBUG, TAG, "OUT");
884     return CA_STATUS_OK;
885 }
886
887 CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
888                                    const CAResponseInfo_t *response)
889 {
890     OIC_LOG(DEBUG, TAG, "IN");
891     VERIFY_NON_NULL(object, TAG, "object");
892     VERIFY_NON_NULL(response, TAG, "response");
893
894     if (false == CAIsSelectedNetworkAvailable())
895     {
896         return CA_STATUS_FAILED;
897     }
898
899     CAData_t *data = CAPrepareSendData(object, response, CA_RESPONSE_DATA);
900     if(!data)
901     {
902         OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
903         return CA_MEMORY_ALLOC_FAILED;
904     }
905
906 #ifdef SINGLE_THREAD
907     CAResult_t result = CAProcessSendData(data);
908     if(result != CA_STATUS_OK)
909     {
910         OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
911         return result;
912     }
913
914     CADestroyData(data, sizeof(CAData_t));
915 #else
916 #ifdef WITH_BWT
917     if (CA_ADAPTER_GATT_BTLE != object->adapter)
918     {
919         // send block data
920         CAResult_t res = CASendBlockWiseData(data);
921         if(CA_NOT_SUPPORTED == res)
922         {
923             OIC_LOG(DEBUG, TAG, "normal msg will be sent");
924             CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
925             return CA_STATUS_OK;
926         }
927         else
928         {
929             CADestroyData(data, sizeof(CAData_t));
930         }
931         return res;
932     }
933     else
934 #endif
935     {
936         CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
937     }
938 #endif
939
940     OIC_LOG(DEBUG, TAG, "OUT");
941     return CA_STATUS_OK;
942 }
943
944 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
945                                       uint8_t tokenLength, const CAHeaderOption_t *options,
946                                       uint8_t numOptions)
947 {
948     return CA_NOT_SUPPORTED;
949 }
950
951 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
952                              CAErrorCallback errorHandler)
953 {
954     OIC_LOG(DEBUG, TAG, "IN");
955     g_requestHandler = ReqHandler;
956     g_responseHandler = RespHandler;
957     g_errorHandler = errorHandler;
958     OIC_LOG(DEBUG, TAG, "OUT");
959 }
960
961 CAResult_t CAInitializeMessageHandler()
962 {
963     OIC_LOG(DEBUG, TAG, "IN");
964     CASetPacketReceivedCallback(CAReceivedPacketCallback);
965
966     CASetNetworkChangeCallback(CANetworkChangedCallback);
967     CASetErrorHandleCallback(CAErrorHandler);
968
969 #ifndef SINGLE_THREAD
970     // create thread pool
971     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
972
973     if (CA_STATUS_OK != res)
974     {
975         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
976         return res;
977     }
978
979     // send thread initialize
980     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
981                                                    CASendThreadProcess, CADestroyData))
982     {
983         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
984         return CA_STATUS_FAILED;
985     }
986
987     // start send thread
988     res = CAQueueingThreadStart(&g_sendThread);
989
990     if (CA_STATUS_OK != res)
991     {
992         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
993         ca_thread_pool_free(g_threadPoolHandle);
994         g_threadPoolHandle = NULL;
995         return res;
996     }
997
998     // receive thread initialize
999     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1000                                                    CAReceiveThreadProcess, CADestroyData))
1001     {
1002         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1003         return CA_STATUS_FAILED;
1004     }
1005
1006 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1007     // start receive thread
1008     res = CAQueueingThreadStart(&gReceiveThread);
1009
1010     if (res != CA_STATUS_OK)
1011     {
1012         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1013         return res;
1014     }
1015 #endif /* SINGLE_HANDLE */
1016
1017     // retransmission initialize
1018     CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
1019                                CATimeoutCallback, NULL);
1020
1021 #ifdef WITH_BWT
1022     // block-wise transfer initialize
1023     CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1024 #endif
1025
1026     // start retransmission
1027     res = CARetransmissionStart(&g_retransmissionContext);
1028
1029     if (CA_STATUS_OK != res)
1030     {
1031         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1032         return res;
1033     }
1034
1035     // initialize interface adapters by controller
1036     CAInitializeAdapters(g_threadPoolHandle);
1037 #else
1038     // retransmission initialize
1039     CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1040                                CATimeoutCallback, NULL);
1041     CAInitializeAdapters();
1042 #endif
1043
1044     OIC_LOG(DEBUG, TAG, "OUT");
1045     return CA_STATUS_OK;
1046 }
1047
1048 void CATerminateMessageHandler()
1049 {
1050     OIC_LOG(DEBUG, TAG, "IN");
1051 #ifndef SINGLE_THREAD
1052     CATransportAdapter_t connType;
1053     u_arraylist_t *list = CAGetSelectedNetworkList();
1054     uint32_t length = u_arraylist_length(list);
1055
1056     uint32_t i = 0;
1057     for (i = 0; i < length; i++)
1058     {
1059         void* ptrType = u_arraylist_get(list, i);
1060
1061         if (NULL == ptrType)
1062         {
1063             continue;
1064         }
1065
1066         connType = *(CATransportAdapter_t *)ptrType;
1067         CAStopAdapter(connType);
1068     }
1069
1070     // stop retransmission
1071     if (NULL != g_retransmissionContext.threadMutex)
1072     {
1073         CARetransmissionStop(&g_retransmissionContext);
1074     }
1075
1076     // stop thread
1077     // delete thread data
1078     if (NULL != g_sendThread.threadMutex)
1079     {
1080         CAQueueingThreadStop(&g_sendThread);
1081     }
1082
1083     // stop thread
1084     // delete thread data
1085     if (NULL != g_receiveThread.threadMutex)
1086     {
1087 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1088         CAQueueingThreadStop(&gReceiveThread);
1089 #endif /* SINGLE_HANDLE */
1090     }
1091
1092     // destroy thread pool
1093     if (NULL != g_threadPoolHandle)
1094     {
1095         ca_thread_pool_free(g_threadPoolHandle);
1096         g_threadPoolHandle = NULL;
1097     }
1098
1099 #ifdef WITH_BWT
1100     CATerminateBlockWiseTransfer();
1101 #endif
1102     CARetransmissionDestroy(&g_retransmissionContext);
1103     CAQueueingThreadDestroy(&g_sendThread);
1104     CAQueueingThreadDestroy(&g_receiveThread);
1105
1106     // terminate interface adapters by controller
1107     CATerminateAdapters();
1108 #else
1109     // terminate interface adapters by controller
1110     CATerminateAdapters();
1111
1112     // stop retransmission
1113     CARetransmissionStop(&g_retransmissionContext);
1114     CARetransmissionDestroy(&g_retransmissionContext);
1115 #endif
1116
1117     OIC_LOG(DEBUG, TAG, "OUT");
1118 }
1119
1120 void CALogPDUInfo(coap_pdu_t *pdu)
1121 {
1122     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1123
1124     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1125
1126     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
1127
1128     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
1129
1130     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1131
1132     OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
1133 }
1134
1135 static void CALogPayloadInfo(CAInfo_t *info)
1136 {
1137     if(info)
1138     {
1139         if (!info->options)
1140         {
1141             for (uint32_t i = 0; i < info->numOptions; i++)
1142             {
1143                 OIC_LOG_V(DEBUG, TAG, "optionID: %d", info->options[i].optionID);
1144
1145                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1146             }
1147         }
1148
1149         if (!info->payload)
1150         {
1151             OIC_LOG_V(DEBUG, TAG, "payload: %p(%u)", info->payload,
1152                       info->payloadSize);
1153         }
1154
1155         if (!info->token)
1156         {
1157             OIC_LOG(DEBUG, TAG, "token:");
1158             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1159                            info->tokenLength);
1160         }
1161         OIC_LOG_V(DEBUG, TAG, "msgID: %d", info->messageId);
1162     }
1163     else
1164     {
1165         OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1166     }
1167 }
1168
1169 void CAErrorHandler(const CAEndpoint_t *endpoint,
1170                     const void *data, uint32_t dataLen,
1171                     CAResult_t result)
1172 {
1173     OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1174
1175 #ifndef SINGLE_THREAD
1176
1177     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1178     VERIFY_NON_NULL_VOID(data, TAG, "data");
1179
1180     uint32_t code = CA_NOT_FOUND;
1181     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1182     //Get PDU data
1183     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code);
1184     if (NULL == pdu)
1185     {
1186         OIC_LOG(ERROR, TAG, "Parse PDU failed");
1187         return;
1188     }
1189
1190     CAData_t *cadata = CAGenerateHandlerData(endpoint, pdu, CA_ERROR_DATA);
1191     if(!cadata)
1192     {
1193         OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1194         coap_delete_pdu(pdu);
1195         return;
1196     }
1197
1198     cadata->errorInfo->result = result;
1199
1200     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1201     coap_delete_pdu(pdu);
1202 #endif
1203
1204     OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1205     return;
1206 }
1207
1208 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1209 {
1210     OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1211 #ifndef SINGLE_THREAD
1212     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1213     if (!cadata)
1214     {
1215         OIC_LOG(ERROR, TAG, "memory allocation failed");
1216         return;
1217     }
1218
1219     CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1220     if (!ep)
1221     {
1222         OIC_LOG(ERROR, TAG, "endpoint clone failed");
1223         OICFree(cadata);
1224         return;
1225     }
1226
1227     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1228     if (!errorInfo)
1229     {
1230         OICFree(cadata);
1231         CAFreeEndpoint(ep);
1232         return;
1233     }
1234
1235     CAResult_t res = CACloneInfo(info, &errorInfo->info);
1236     if (CA_STATUS_OK != res)
1237     {
1238         OICFree(cadata);
1239         CAFreeEndpoint(ep);
1240         return;
1241     }
1242
1243     errorInfo->result = result;
1244     cadata->remoteEndpoint = ep;
1245     cadata->errorInfo = errorInfo;
1246     cadata->dataType = CA_ERROR_DATA;
1247
1248     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1249 #endif
1250     OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1251 }