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