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