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