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