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