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