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