[IOT-583] fixed Option Parameter is not support
[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         CAAdapterFreeEndpoint(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         CAAdapterFreeEndpoint(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         CAAdapterFreeEndpoint(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         CADestroyEndpointInternal(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(cadata->errorInfo);
188     }
189
190     OICFree(cadata);
191     OIC_LOG(DEBUG, TAG, "OUT");
192 }
193
194 static void CAReceiveThreadProcess(void *threadData)
195 {
196     OIC_LOG(DEBUG, TAG, "IN");
197     // Currently not supported
198     // This will be enabled when RI supports multi threading
199 #ifndef SINGLE_HANDLE
200     CAData_t *data = (CAData_t *) threadData;
201
202     if (NULL == data)
203     {
204         OIC_LOG(ERROR, TAG, "thread data error!!");
205         return;
206     }
207
208     // parse the data and call the callbacks.
209     // #1 parse the data
210     // #2 get endpoint
211     CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
212
213     if (NULL == rep)
214     {
215         OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
216         return;
217     }
218
219     if (data->requestInfo && g_requestHandler)
220     {
221         g_requestHandler(rep, data->requestInfo);
222     }
223     else if (data->responseInfo && g_responseHandler)
224     {
225         g_responseHandler(rep, data->responseInfo);
226     }
227     else if (data->errorInfo && g_errorHandler)
228     {
229         g_errorHandler(rep, data->errorInfo);
230     }
231
232 #endif /* SINGLE_HANDLE */
233     OIC_LOG(DEBUG, TAG, "OUT");
234 }
235
236 static void CASendThreadProcess(void *threadData)
237 {
238     OIC_LOG(DEBUG, TAG, "IN");
239     CAData_t *data = (CAData_t *) threadData;
240
241     VERIFY_NON_NULL_VOID(data, TAG, "data");
242     VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG, "remoteEndpoint");
243
244     CAResult_t res = CA_STATUS_FAILED;
245
246     CASendDataType_t type = data->type;
247
248     coap_pdu_t *pdu = NULL;
249
250     if (SEND_TYPE_UNICAST == type)
251     {
252
253         if (NULL != data->requestInfo)
254         {
255             OIC_LOG(DEBUG, TAG, "requestInfo is available..");
256
257             pdu = CAGeneratePDU(data->requestInfo->method, &data->requestInfo->info);
258         }
259         else if (NULL != data->responseInfo)
260         {
261             OIC_LOG(DEBUG, TAG, "responseInfo is available..");
262
263             pdu = CAGeneratePDU(data->responseInfo->result, &data->responseInfo->info);
264         }
265         else
266         {
267             OIC_LOG(DEBUG, TAG, "request info, response info is empty");
268         }
269
270         // interface controller function call.
271         if (NULL != pdu)
272         {
273             CALogPDUInfo(pdu);
274
275             res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
276             if (CA_STATUS_OK != res)
277             {
278                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
279                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, 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                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
315                 coap_delete_pdu(pdu);
316                 return;
317             }
318
319             coap_delete_pdu(pdu);
320         }
321     }
322
323     OIC_LOG(DEBUG, TAG, "OUT");
324 }
325
326 static void CAReceivedPacketCallback(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
327 {
328     OIC_LOG(DEBUG, TAG, "IN");
329     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
330     VERIFY_NON_NULL_VOID(data, TAG, "data");
331
332     uint32_t code = CA_NOT_FOUND;
333     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
334     OICFree(data);
335
336     if (NULL == pdu)
337     {
338         OIC_LOG(ERROR, TAG, "Parse PDU failed");
339         return;
340     }
341
342     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
343     {
344         CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
345         if (NULL == ReqInfo)
346         {
347             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
348             coap_delete_pdu(pdu);
349             return;
350         }
351
352         CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo);
353         if (CA_STATUS_OK != res)
354         {
355             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
356             OICFree(ReqInfo);
357             coap_delete_pdu(pdu);
358             return;
359         }
360
361         if (NULL != ReqInfo->info.options)
362         {
363             uint32_t i;
364             for (i = 0; i < ReqInfo->info.numOptions; i++)
365             {
366                 OIC_LOG_V(DEBUG, TAG, "Request- optionID: %d", ReqInfo->info.options[i].optionID);
367
368                 OIC_LOG_V(DEBUG, TAG, "Request- list: %s", ReqInfo->info.options[i].optionData);
369             }
370         }
371
372         if (NULL != ReqInfo->info.payload)
373         {
374             OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
375         }
376         OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
377         if (NULL != ReqInfo->info.token)
378         {
379             OIC_LOG(DEBUG, TAG, "Request- token:");
380             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token,
381                            ReqInfo->info.tokenLength);
382         }
383         OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
384         // store the data at queue.
385         CAData_t *cadata = NULL;
386         cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
387         if (NULL == cadata)
388         {
389             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
390             CADestroyRequestInfoInternal(ReqInfo);
391             coap_delete_pdu(pdu);
392             return;
393         }
394
395         cadata->type = SEND_TYPE_UNICAST;
396         cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
397         cadata->requestInfo = ReqInfo;
398         cadata->responseInfo = NULL;
399         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
400     }
401     else
402     {
403         CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
404         if (NULL == ResInfo)
405         {
406             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
407             coap_delete_pdu(pdu);
408             return;
409         }
410
411         CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo);
412         if (CA_STATUS_OK != res)
413         {
414             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
415             OICFree(ResInfo);
416             coap_delete_pdu(pdu);
417             return;
418         }
419
420         if (NULL != ResInfo->info.options)
421         {
422             uint32_t i;
423             for (i = 0; i < ResInfo->info.numOptions; i++)
424             {
425                 OIC_LOG_V(DEBUG, TAG, "Response- optionID: %d", ResInfo->info.options[i].optionID);
426
427                 OIC_LOG_V(DEBUG, TAG, "Response- list: %s", ResInfo->info.options[i].optionData);
428             }
429         }
430
431         if (NULL != ResInfo->info.payload)
432         {
433             OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
434         }
435         OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
436         if (NULL != ResInfo->info.token)
437         {
438             OIC_LOG(DEBUG, TAG, "Response- token:");
439             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ResInfo->info.token,
440                            ResInfo->info.tokenLength);
441         }
442         OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
443
444         // store the data at queue.
445         CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
446         if (NULL == cadata)
447         {
448             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
449             CADestroyResponseInfoInternal(ResInfo);
450             coap_delete_pdu(pdu);
451             return;
452         }
453
454         cadata->type = SEND_TYPE_UNICAST;
455         cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
456         cadata->requestInfo = NULL;
457
458         // for retransmission
459         void *retransmissionPdu = NULL;
460         CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length,
461                                      &retransmissionPdu);
462
463         // get token from saved data in retransmission list
464         if (retransmissionPdu && CA_EMPTY == code)
465         {
466             CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
467                                                &(ResInfo->info));
468             if (CA_STATUS_OK != res)
469             {
470                 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
471                 OICFree(ResInfo->info.token);
472             }
473         }
474         OICFree(retransmissionPdu);
475         cadata->responseInfo = ResInfo;
476
477         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
478     }
479
480     if (pdu)
481     {
482         coap_delete_pdu(pdu);
483     }
484     OIC_LOG(DEBUG, TAG, "OUT");
485 }
486
487 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
488 {
489     OIC_LOG(DEBUG, TAG, "IN");
490
491     OIC_LOG(DEBUG, TAG, "OUT");
492 }
493
494 void CAHandleRequestResponseCallbacks()
495 {
496
497 #ifdef SINGLE_HANDLE
498     // parse the data and call the callbacks.
499     // #1 parse the data
500     // #2 get endpoint
501
502     ca_mutex_lock(g_receiveThread.threadMutex);
503
504     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
505
506     ca_mutex_unlock(g_receiveThread.threadMutex);
507
508     if (NULL == item)
509     {
510         return;
511     }
512
513     // get values
514     void *msg = item->msg;
515
516     if (NULL == msg)
517     {
518         return;
519     }
520
521     // get endpoint
522     CAData_t *td = (CAData_t *) msg;
523
524     if (td->requestInfo && g_requestHandler)
525     {
526         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
527         g_requestHandler(td->remoteEndpoint, td->requestInfo);
528     }
529     else if (td->responseInfo && g_responseHandler)
530     {
531         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
532         g_responseHandler(td->remoteEndpoint, td->responseInfo);
533     }
534     else if (td->errorInfo && g_errorHandler)
535     {
536         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
537         g_errorHandler(td->remoteEndpoint, td->errorInfo);
538     }
539
540     CADataDestroyer(msg, sizeof(CAData_t));
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     CAAdapterFreeEndpoint(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     CAAdapterFreeEndpoint(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         CADestroyEndpointInternal(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 }