Imported Upstream version 0.9.1
[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 = data->requestInfo->info;
282
283         info.options = data->options;
284         info.numOptions = data->numOptions;
285
286         coap_pdu_t *pdu = (coap_pdu_t *) CAGeneratePDU(data->remoteEndpoint->resourceUri, CA_GET,
287                                                        info);
288
289         if (NULL != pdu)
290         {
291             CALogPDUInfo(pdu);
292
293             res = CASendMulticastData(pdu->hdr, pdu->length);
294             if(CA_STATUS_OK != res)
295             {
296                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
297                 coap_delete_pdu(pdu);
298                 return;
299             }
300
301             coap_delete_pdu(pdu);
302         }
303     }
304
305     OIC_LOG(DEBUG, TAG, "OUT");
306 }
307
308 static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
309 {
310     OIC_LOG(DEBUG, TAG, "IN");
311     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
312     VERIFY_NON_NULL_VOID(data, TAG, "data");
313
314     uint32_t code = CA_NOT_FOUND;
315     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
316     OICFree(data);
317
318     if (NULL == pdu)
319     {
320         OIC_LOG(ERROR, TAG, "Parse PDU failed");
321         CAAdapterFreeRemoteEndpoint(endpoint);
322         return;
323     }
324
325     char uri[CA_MAX_URI_LENGTH] = { 0, };
326     uint32_t bufLen = sizeof(uri);
327
328     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
329     {
330         CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
331         if (NULL == ReqInfo)
332         {
333             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
334             coap_delete_pdu(pdu);
335             CAAdapterFreeRemoteEndpoint(endpoint);
336             return;
337         }
338
339         CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo, uri, bufLen);
340         if (CA_STATUS_OK != res)
341         {
342             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
343             OICFree(ReqInfo);
344             coap_delete_pdu(pdu);
345             CAAdapterFreeRemoteEndpoint(endpoint);
346             return;
347         }
348
349         if (NULL != ReqInfo->info.options)
350         {
351             uint32_t i;
352             for (i = 0; i < ReqInfo->info.numOptions; i++)
353             {
354                 OIC_LOG_V(DEBUG, TAG, "Request- optionID: %d", ReqInfo->info.options[i].optionID);
355
356                 OIC_LOG_V(DEBUG, TAG, "Request- list: %s", ReqInfo->info.options[i].optionData);
357             }
358         }
359
360         if (NULL != ReqInfo->info.payload)
361         {
362             OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
363         }
364         OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
365         if (NULL != ReqInfo->info.token)
366         {
367             OIC_LOG(DEBUG, TAG, "Request- token:");
368             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token,
369                            ReqInfo->info.tokenLength);
370         }
371
372         OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
373         OIC_LOG(DEBUG, TAG, "Request- token");
374         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
375         OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
376         if (NULL != endpoint)
377         {
378             endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
379             if (NULL == endpoint->resourceUri)
380             {
381                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
382                 OICFree(ReqInfo);
383                 coap_delete_pdu(pdu);
384                 CAAdapterFreeRemoteEndpoint(endpoint);
385                 return;
386             }
387             memcpy(endpoint->resourceUri, uri, bufLen);
388             endpoint->resourceUri[bufLen] = '\0';
389             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
390         }
391         // store the data at queue.
392         CAData_t *cadata = NULL;
393         cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
394         if (NULL == cadata)
395         {
396             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
397             OICFree(ReqInfo);
398             coap_delete_pdu(pdu);
399             CAAdapterFreeRemoteEndpoint(endpoint);
400             return;
401         }
402
403         cadata->type = SEND_TYPE_UNICAST;
404         cadata->remoteEndpoint = endpoint;
405         cadata->requestInfo = ReqInfo;
406         cadata->responseInfo = NULL;
407         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
408     }
409     else
410     {
411         CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
412         if (NULL == ResInfo)
413         {
414             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
415             coap_delete_pdu(pdu);
416             CAAdapterFreeRemoteEndpoint(endpoint);
417             return;
418         }
419
420         CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo, uri, bufLen);
421         if (CA_STATUS_OK != res)
422         {
423             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
424             OICFree(ResInfo);
425             coap_delete_pdu(pdu);
426             CAAdapterFreeRemoteEndpoint(endpoint);
427             return;
428         }
429
430         if (NULL != ResInfo->info.options)
431         {
432             uint32_t i;
433             for (i = 0; i < ResInfo->info.numOptions; i++)
434             {
435                 OIC_LOG_V(DEBUG, TAG, "Response- optionID: %d", ResInfo->info.options[i].optionID);
436
437                 OIC_LOG_V(DEBUG, TAG, "Response- list: %s", ResInfo->info.options[i].optionData);
438             }
439         }
440
441         if (NULL != ResInfo->info.payload)
442         {
443             OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
444         }
445         OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
446         OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
447         OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
448
449         if (NULL != endpoint)
450         {
451             endpoint->resourceUri = (char *) OICMalloc(bufLen + 1);
452             if (NULL == endpoint->resourceUri)
453             {
454                 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
455                 OICFree(ResInfo);
456                 coap_delete_pdu(pdu);
457                 CAAdapterFreeRemoteEndpoint(endpoint);
458                 return;
459             }
460             memcpy(endpoint->resourceUri, uri, bufLen);
461             endpoint->resourceUri[bufLen] = '\0';
462             OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
463         }
464
465         // store the data at queue.
466         CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
467         if (NULL == cadata)
468         {
469             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
470             OICFree(ResInfo);
471             coap_delete_pdu(pdu);
472             CAAdapterFreeRemoteEndpoint(endpoint);
473             return;
474         }
475
476         cadata->type = SEND_TYPE_UNICAST;
477         cadata->remoteEndpoint = endpoint;
478         cadata->requestInfo = NULL;
479
480         // for retransmission
481         void *retransmissionPdu = NULL;
482         CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
483                                      &retransmissionPdu);
484
485         // get token from saved data in retransmission list
486         if (retransmissionPdu && CA_EMPTY == code)
487         {
488             CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
489                                                &(ResInfo->info));
490             if (CA_STATUS_OK != res)
491             {
492                 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
493                 OICFree(ResInfo->info.token);
494             }
495         }
496         OICFree(retransmissionPdu);
497         cadata->responseInfo = ResInfo;
498
499         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
500     }
501
502     if (pdu)
503     {
504         coap_delete_pdu(pdu);
505     }
506     OIC_LOG(DEBUG, TAG, "OUT");
507 }
508
509 static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
510 {
511     OIC_LOG(DEBUG, TAG, "IN");
512
513     OIC_LOG(DEBUG, TAG, "OUT");
514 }
515
516 void CAHandleRequestResponseCallbacks()
517 {
518     OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks IN");
519
520 #ifdef SINGLE_HANDLE
521     // parse the data and call the callbacks.
522     // #1 parse the data
523     // #2 get endpoint
524
525     ca_mutex_lock(g_receiveThread.threadMutex);
526
527     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
528
529     ca_mutex_unlock(g_receiveThread.threadMutex);
530
531     if (NULL == item)
532     {
533         return;
534     }
535
536     // get values
537     void *msg = item->msg;
538
539     if (NULL == msg)
540     {
541         return;
542     }
543
544     // get endpoint
545     CAData_t *td = (CAData_t *) msg;
546     CARemoteEndpoint_t *rep = td->remoteEndpoint;
547
548     if (NULL == rep)
549     {
550         return;
551     }
552
553     if (NULL != td->requestInfo)
554     {
555         if (g_requestHandler)
556         {
557             OIC_LOG_V(DEBUG, TAG, "callback will be sent : %d", td->requestInfo->info.numOptions);
558             g_requestHandler(rep, td->requestInfo);
559         }
560     }
561
562     if (NULL != td->responseInfo)
563     {
564         if (g_responseHandler)
565         {
566             g_responseHandler(rep, td->responseInfo);
567         }
568
569     }
570     CADataDestroyer(msg, sizeof(CAData_t));
571
572 #endif
573     OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks OUT");
574 }
575
576 CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
577 {
578     OIC_LOG(DEBUG, TAG, "IN");
579
580     VERIFY_NON_NULL(object, TAG, "object");
581     VERIFY_NON_NULL(request, TAG, "request");
582
583     if (false == CAIsSelectedNetworkAvailable())
584     {
585         return CA_STATUS_FAILED;
586     }
587
588     CARemoteEndpoint_t *remoteEndpoint = NULL;
589     CARequestInfo_t *requestInfo = NULL;
590     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
591     CA_MEMORY_ALLOC_CHECK(data);
592
593     // clone remote endpoint
594     remoteEndpoint = CACloneRemoteEndpoint(object);
595     CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
596
597     // clone request info
598     requestInfo = CACloneRequestInfo(request);
599     CA_MEMORY_ALLOC_CHECK(requestInfo);
600
601     // save data
602     data->type = SEND_TYPE_UNICAST;
603     data->remoteEndpoint = remoteEndpoint;
604     data->requestInfo = requestInfo;
605     data->responseInfo = NULL;
606
607     // add thread
608     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
609     OIC_LOG(DEBUG, TAG, "OUT");
610     return CA_STATUS_OK;
611
612 // memory error label.
613 memory_error_exit:
614     CADestroyRemoteEndpointInternal(remoteEndpoint);
615     CADestroyRequestInfoInternal(requestInfo);
616
617     OICFree(data);
618     OIC_LOG(DEBUG, TAG, "OUT");
619     return CA_MEMORY_ALLOC_FAILED;
620 }
621
622 CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
623                                        const CARequestInfo_t *request)
624 {
625     OIC_LOG(DEBUG, TAG, "IN");
626
627     if (NULL == object || NULL == request || NULL == object->resourceUri)
628     {
629         return CA_STATUS_INVALID_PARAM;
630     }
631
632     if ((request->method < CA_GET) || (request->method > CA_DELETE))
633     {
634         OIC_LOG(ERROR, TAG, "Invalid method type!");
635
636         return CA_STATUS_INVALID_PARAM;
637     }
638
639     if (false == CAIsSelectedNetworkAvailable())
640     {
641         return CA_STATUS_FAILED;
642     }
643
644     CARemoteEndpoint_t *remoteEndpoint = NULL;
645     CARequestInfo_t *requestInfo = NULL;
646
647     // allocate & initialize
648     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
649     CA_MEMORY_ALLOC_CHECK(data);
650
651     CAAddress_t addr = {};
652     remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
653                                                     object->transportType);
654
655     // clone request info
656     requestInfo = CACloneRequestInfo(request);
657     CA_MEMORY_ALLOC_CHECK(requestInfo);
658
659     // save data
660     data->type = SEND_TYPE_MULTICAST;
661     data->remoteEndpoint = remoteEndpoint;
662     data->requestInfo = requestInfo;
663     data->responseInfo = NULL;
664
665     // add thread
666     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
667
668     OIC_LOG(DEBUG, TAG, "OUT");
669     return CA_STATUS_OK;
670
671 // memory error label.
672 memory_error_exit:
673
674     CADestroyRequestInfoInternal(requestInfo);
675     CADestroyRemoteEndpointInternal(remoteEndpoint);
676     OICFree(data);
677     OIC_LOG(DEBUG, TAG, "OUT");
678     return CA_MEMORY_ALLOC_FAILED;
679 }
680
681 CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
682                                    const CAResponseInfo_t *response)
683 {
684     OIC_LOG(DEBUG, TAG, "IN");
685     VERIFY_NON_NULL(object, TAG, "object");
686     VERIFY_NON_NULL(response, TAG, "response");
687
688     if (false == CAIsSelectedNetworkAvailable())
689     {
690         return CA_STATUS_FAILED;
691     }
692
693     CARemoteEndpoint_t *remoteEndpoint = NULL;
694     CAResponseInfo_t *responseInfo = NULL;
695
696     // allocate & initialize
697     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
698     CA_MEMORY_ALLOC_CHECK(data);
699
700     // clone remote endpoint
701     remoteEndpoint = CACloneRemoteEndpoint(object);
702     CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
703
704     // clone response info
705     responseInfo = CACloneResponseInfo(response);
706     CA_MEMORY_ALLOC_CHECK(responseInfo);
707
708     // save data
709     data->type = SEND_TYPE_UNICAST;
710     data->remoteEndpoint = remoteEndpoint;
711     data->requestInfo = NULL;
712     data->responseInfo = responseInfo;
713
714     // add thread
715     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
716
717     OIC_LOG(DEBUG, TAG, "OUT");
718     return CA_STATUS_OK;
719
720 // memory error label.
721 memory_error_exit:
722     CADestroyRemoteEndpointInternal(remoteEndpoint);
723     CADestroyResponseInfoInternal(responseInfo);
724     OICFree(data);
725     OIC_LOG(DEBUG, TAG, "OUT");
726
727     return CA_MEMORY_ALLOC_FAILED;
728 }
729
730 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
731                                       uint8_t tokenLength, const CAHeaderOption_t *options,
732                                       uint8_t numOptions)
733 {
734     OIC_LOG(DEBUG, TAG, "IN");
735     VERIFY_NON_NULL(resourceUri, TAG, "resourceUri is NULL");
736     VERIFY_NON_NULL(token, TAG, "Token is NULL");
737
738     if (false == CAIsSelectedNetworkAvailable())
739     {
740         return CA_STATUS_FAILED;
741     }
742
743     CARemoteEndpoint_t *remoteEndpoint = NULL;
744     CARequestInfo_t *reqInfo = NULL;
745     char *tempToken = NULL;
746
747     // allocate & initialize
748     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
749     CA_MEMORY_ALLOC_CHECK(data);
750
751     CAAddress_t addr = {};
752     remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
753                                                     CA_IPV4 | CA_EDR | CA_LE);
754
755     // create request info
756     reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
757     CA_MEMORY_ALLOC_CHECK(reqInfo);
758
759     if (tokenLength)
760     {
761         // copy token value
762         tempToken = (char *) OICMalloc(tokenLength);
763         CA_MEMORY_ALLOC_CHECK(tempToken);
764         memcpy(tempToken, token, tokenLength);
765     }
766
767     // save request info data
768     reqInfo->method = CA_GET;
769     reqInfo->info.type = CA_MSG_NONCONFIRM;
770
771     reqInfo->info.token = tempToken;
772     reqInfo->info.tokenLength = tokenLength;
773
774     // save data
775     data->type = SEND_TYPE_MULTICAST;
776     data->remoteEndpoint = remoteEndpoint;
777     data->requestInfo = reqInfo;
778
779     data->responseInfo = NULL;
780     data->options = NULL;
781     data->numOptions = 0;
782     if (NULL != options && 0 < numOptions)
783     {
784         // copy data
785         CAHeaderOption_t *headerOption = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t)
786                                                                         * numOptions);
787         CA_MEMORY_ALLOC_CHECK(headerOption);
788
789         memcpy(headerOption, options, sizeof(CAHeaderOption_t) * numOptions);
790
791         data->options = headerOption;
792         data->numOptions = numOptions;
793     }
794
795     // add thread
796     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
797
798     OIC_LOG(DEBUG, TAG, "OUT");
799     return CA_STATUS_OK;
800
801 // memory error label.
802 memory_error_exit:
803
804     CADestroyRemoteEndpointInternal(remoteEndpoint);
805
806     OICFree(tempToken);
807     OICFree(reqInfo);
808     OICFree(data);
809     OIC_LOG(DEBUG, TAG, "OUT");
810     return CA_MEMORY_ALLOC_FAILED;
811 }
812
813 void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
814 {
815     OIC_LOG(DEBUG, TAG, "IN");
816     g_requestHandler = ReqHandler;
817     g_responseHandler = RespHandler;
818     OIC_LOG(DEBUG, TAG, "OUT");
819 }
820
821 CAResult_t CAInitializeMessageHandler()
822 {
823     OIC_LOG(DEBUG, TAG, "IN");
824     CASetPacketReceivedCallback(CAReceivedPacketCallback);
825
826     CASetNetworkChangeCallback(CANetworkChangedCallback);
827
828     // create thread pool
829     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
830
831     if (res != CA_STATUS_OK)
832     {
833         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
834         return res;
835     }
836
837     // send thread initialize
838     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
839                                                    CASendThreadProcess, CADataDestroyer))
840     {
841         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
842         return CA_STATUS_FAILED;
843     }
844
845     // start send thread
846     res = CAQueueingThreadStart(&g_sendThread);
847
848     if (res != CA_STATUS_OK)
849     {
850         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
851         ca_thread_pool_free(g_threadPoolHandle);
852         g_threadPoolHandle = NULL;
853         return res;
854     }
855
856     // receive thread initialize
857     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
858                                                    CAReceiveThreadProcess, CADataDestroyer))
859     {
860         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
861         return CA_STATUS_FAILED;
862     }
863
864 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
865     // start receive thread
866     res = CAQueueingThreadStart(&gReceiveThread);
867
868     if (res != CA_STATUS_OK)
869     {
870         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
871         return res;
872     }
873 #endif
874
875     // retransmission initialize
876     CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
877                                CATimeoutCallback, NULL);
878
879     // start retransmission
880     res = CARetransmissionStart(&g_retransmissionContext);
881
882     if (res != CA_STATUS_OK)
883     {
884         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
885         return res;
886     }
887
888     // initialize interface adapters by controller
889     CAInitializeAdapters(g_threadPoolHandle);
890     OIC_LOG(DEBUG, TAG, "OUT");
891     return CA_STATUS_OK;
892 }
893
894 void CATerminateMessageHandler()
895 {
896     OIC_LOG(DEBUG, TAG, "IN");
897     CATransportType_t connType;
898     u_arraylist_t *list = CAGetSelectedNetworkList();
899     uint32_t length = u_arraylist_length(list);
900
901     uint32_t i = 0;
902     for (i = 0; i < length; i++)
903     {
904         void* ptrType = u_arraylist_get(list, i);
905
906         if (NULL == ptrType)
907         {
908             continue;
909         }
910
911         connType = *(CATransportType_t *) ptrType;
912         CAStopAdapter(connType);
913     }
914
915     // stop retransmission
916     if (NULL != g_retransmissionContext.threadMutex)
917     {
918         CARetransmissionStop(&g_retransmissionContext);
919     }
920
921     // stop thread
922     // delete thread data
923     if (NULL != g_sendThread.threadMutex)
924     {
925         CAQueueingThreadStop(&g_sendThread);
926     }
927
928     // stop thread
929     // delete thread data
930     if (NULL != g_receiveThread.threadMutex)
931     {
932 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
933         CAQueueingThreadStop(&gReceiveThread);
934 #endif
935     }
936
937     // destroy thread pool
938     if (NULL != g_threadPoolHandle)
939     {
940         ca_thread_pool_free(g_threadPoolHandle);
941         g_threadPoolHandle = NULL;
942     }
943
944     CARetransmissionDestroy(&g_retransmissionContext);
945     CAQueueingThreadDestroy(&g_sendThread);
946     CAQueueingThreadDestroy(&g_receiveThread);
947
948     // terminate interface adapters by controller
949     CATerminateAdapters();
950
951     OIC_LOG(DEBUG, TAG, "OUT");
952 }
953
954 void CALogPDUInfo(coap_pdu_t *pdu)
955 {
956     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
957
958     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
959
960     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
961
962     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
963
964     OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
965
966     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
967
968     OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
969 }