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