Replace/examine usages of mem* and strcat/strcpy
[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 "oic_string.h"
41 #include "canetworkconfigurator.h"
42
43 #define TAG PCF("CA")
44 #define SINGLE_HANDLE
45
46 #define MAX_THREAD_POOL_SIZE    20
47
48 typedef enum
49 {
50     SEND_TYPE_MULTICAST = 0, SEND_TYPE_UNICAST
51 } CASendDataType_t;
52
53 typedef enum
54 {
55     CA_REQUEST_DATA = 1,
56     CA_RESPONSE_DATA = 2,
57     CA_ERROR_DATA = 3,
58 } CADataType_t;
59
60 typedef struct
61 {
62     CASendDataType_t type;
63     CARemoteEndpoint_t *remoteEndpoint;
64     CARequestInfo_t *requestInfo;
65     CAResponseInfo_t *responseInfo;
66     CAErrorInfo_t *errorInfo;
67     CAHeaderOption_t *options;
68     CADataType_t dataType;
69     uint8_t numOptions;
70 } CAData_t;
71
72 // thread pool handle
73 static ca_thread_pool_t g_threadPoolHandle = NULL;
74
75 // message handler main thread
76 static CAQueueingThread_t g_sendThread;
77 static CAQueueingThread_t g_receiveThread;
78
79 static CARetransmission_t g_retransmissionContext;
80
81 // handler field
82 static CARequestCallback g_requestHandler = NULL;
83 static CAResponseCallback g_responseHandler = NULL;
84 static CAErrorCallback g_errorHandler = NULL;
85
86 static void CAErrorHandler(const CARemoteEndpoint_t *remoteEndpoint,
87                            const void *data, uint32_t dataLen, CAResult_t result);
88
89 static bool CAIsSelectedNetworkAvailable()
90 {
91     u_arraylist_t *list = CAGetSelectedNetworkList();
92     if (!list || list->length == 0)
93     {
94         OIC_LOG(ERROR, TAG, "No selected network");
95         return false;
96     }
97
98     return true;
99 }
100
101 static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
102 {
103     OIC_LOG(DEBUG, TAG, "IN");
104     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
105     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
106
107     CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
108     if (NULL == ep)
109     {
110         OIC_LOG(ERROR, TAG, "clone failed");
111         return;
112     }
113
114     CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
115
116     if (NULL == resInfo)
117     {
118         OIC_LOG(ERROR, TAG, "calloc failed");
119         CADestroyRemoteEndpointInternal(ep);
120         return;
121     }
122
123     resInfo->result = CA_RETRANSMIT_TIMEOUT;
124     resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
125     resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
126     CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info));
127     if (CA_STATUS_OK != res)
128     {
129         OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
130         OICFree(resInfo->info.token);
131         OICFree(resInfo);
132         CADestroyRemoteEndpointInternal(ep);
133         return;
134     }
135
136     CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
137     if (NULL == cadata)
138     {
139         OIC_LOG(ERROR, TAG, "memory allocation failed !");
140         CADestroyRemoteEndpointInternal(ep);
141         OICFree(resInfo);
142         return;
143     }
144
145     cadata->type = SEND_TYPE_UNICAST;
146     cadata->remoteEndpoint = ep;
147     cadata->requestInfo = NULL;
148     cadata->responseInfo = resInfo;
149
150     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
151     OIC_LOG(DEBUG, TAG, "OUT");
152 }
153
154 static void CADataDestroyer(void *data, uint32_t size)
155 {
156     OIC_LOG(DEBUG, TAG, "IN");
157     CAData_t *cadata = (CAData_t *) data;
158
159     if (NULL == cadata)
160     {
161         OIC_LOG(ERROR, TAG, "cadata is NULL");
162         return;
163     }
164
165     if (NULL != cadata->remoteEndpoint)
166     {
167         CADestroyRemoteEndpointInternal((CARemoteEndpoint_t *) cadata->remoteEndpoint);
168     }
169
170     if (NULL != cadata->requestInfo)
171     {
172         CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
173     }
174
175     if (NULL != cadata->responseInfo)
176     {
177         CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
178     }
179
180     if (NULL != cadata->errorInfo)
181     {
182        CAInfo_t *info = &cadata->errorInfo->info;
183        OICFree(info->token);
184        OICFree(info->options);
185        OICFree(info->payload);
186        OICFree(cadata->errorInfo);
187     }
188
189     OICFree(cadata->options);
190     OICFree(cadata);
191     OIC_LOG(DEBUG, TAG, "OUT");
192 }
193
194 static void CAReceiveThreadProcess(void *threadData)
195 {
196     OIC_LOG(DEBUG, TAG, "IN");
197     // Currently not supported
198     // This will be enabled when RI supports multi threading
199 #ifndef SINGLE_HANDLE
200     CAData_t *data = (CAData_t *) threadData;
201
202     if (NULL == data)
203     {
204         OIC_LOG(ERROR, TAG, "thread data error!!");
205         return;
206     }
207
208     // parse the data and call the callbacks.
209     // #1 parse the data
210     // #2 get endpoint
211     CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *)(data->remoteEndpoint);
212
213     if (NULL == rep)
214     {
215         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
216         return;
217     }
218
219     if (data->requestInfo && g_requestHandler)
220     {
221         g_requestHandler(rep, data->requestInfo);
222     }
223     else if (data->responseInfo && g_responseHandler)
224     {
225         g_responseHandler(rep, data->responseInfo);
226     }
227     else if (data->errorInfo && g_errorHandler)
228     {
229         g_errorHandler(rep, data->errorInfo);
230     }
231
232 #endif /* SINGLE_HANDLE */
233     OIC_LOG(DEBUG, TAG, "OUT");
234 }
235
236 static void CASendThreadProcess(void *threadData)
237 {
238     OIC_LOG(DEBUG, TAG, "IN");
239     CAData_t *data = (CAData_t *) threadData;
240
241     VERIFY_NON_NULL_VOID(data, TAG, "data");
242     VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "remoteEndpoint");
243
244     CAResult_t res = CA_STATUS_FAILED;
245
246     CASendDataType_t type = data->type;
247
248     if (SEND_TYPE_UNICAST == type)
249     {
250         coap_pdu_t *pdu = NULL;
251
252         if (NULL != data->requestInfo)
253         {
254             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
255
256             pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
257                                                data->requestInfo->method,
258                                                data->requestInfo->info);
259         }
260         else if (NULL != data->responseInfo)
261         {
262             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
263
264             pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri,
265                                                data->responseInfo->result,
266                                                data->responseInfo->info);
267         }
268         else
269         {
270             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
271         }
272
273         // interface controller function call.
274         if (NULL != pdu)
275         {
276             CALogPDUInfo(pdu);
277
278             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
279             if (CA_STATUS_OK != res)
280             {
281                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
282                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
283                 coap_delete_pdu(pdu);
284                 return;
285             }
286             // for retransmission
287             res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
288                                            pdu->length);
289             if (CA_STATUS_OK != res)
290             {
291                 OIC_LOG_V(INFO, TAG, "retransmission will be not working: %d", res);
292                 coap_delete_pdu(pdu);
293                 return;
294             }
295
296             coap_delete_pdu(pdu);
297         }
298     }
299     else if (SEND_TYPE_MULTICAST == type)
300     {
301         OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
302
303         CAInfo_t info = data->requestInfo->info;
304
305         info.options = data->options;
306         info.numOptions = data->numOptions;
307
308         coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
309                                                        info);
310
311         if (NULL != pdu)
312         {
313             CALogPDUInfo(pdu);
314
315             res = CASendMulticastData(pdu->hdr, pdu->length);
316             if(CA_STATUS_OK != res)
317             {
318                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
319                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
320                 coap_delete_pdu(pdu);
321                 return;
322             }
323
324             coap_delete_pdu(pdu);
325         }
326     }
327
328     OIC_LOG(DEBUG, TAG, "OUT");
329 }
330
331 static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
332 {
333     OIC_LOG(DEBUG, TAG, "IN");
334     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
335     VERIFY_NON_NULL_VOID(data, TAG, "data");
336
337     uint32_t code = CA_NOT_FOUND;
338     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
339     OICFree(data);
340
341     if (NULL == pdu)
342     {
343         OIC_LOG(ERROR, TAG, "Parse PDU failed");
344         CAAdapterFreeRemoteEndpoint(endpoint);
345         return;
346     }
347
348     char uri[CA_MAX_URI_LENGTH] = { };
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, sizeof(uri));
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(sizeof(uri) + 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, sizeof(uri));
410             endpoint->resourceUri[sizeof(uri)] = '\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, sizeof(uri));
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(sizeof(uri) + 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, sizeof(uri));
483             endpoint->resourceUri[sizeof(uri)] = '\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         CAURI_t resourceUri = OICStrdup(uri);
1056         if (NULL == resourceUri)
1057         {
1058             OIC_LOG(ERROR, TAG, "CAErrorHandler, Memory allocation failed!");
1059             OICFree(errorInfo);
1060             coap_delete_pdu(pdu);
1061             return;
1062         }
1063
1064         OIC_LOG_V(DEBUG, TAG, "URI : %s", resourceUri);
1065         rep->resourceUri = resourceUri;
1066     }
1067
1068     // store the data at queue.
1069     CAData_t *cadata = NULL;
1070     cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1071     if (NULL == cadata)
1072     {
1073         OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
1074         CADestroyRemoteEndpointInternal(rep);
1075         OICFree(errorInfo);
1076         coap_delete_pdu(pdu);
1077         return;
1078     }
1079
1080     cadata->remoteEndpoint = rep;
1081     cadata->requestInfo = NULL;
1082     cadata->responseInfo = NULL;
1083     cadata->errorInfo = errorInfo;
1084     cadata->dataType = CA_ERROR_DATA;
1085     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1086     coap_delete_pdu(pdu);
1087
1088     return;
1089 }
1090