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