5fcbad397d15ab3aa94eecdf1e350455c0551e7f
[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->options);
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                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
281                 coap_delete_pdu(pdu);
282                 return;
283             }
284             // for retransmission
285             res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
286                                            pdu->length);
287             if (CA_STATUS_OK != res)
288             {
289                 OIC_LOG_V(INFO, TAG, "retransmission will be not working: %d", res);
290                 coap_delete_pdu(pdu);
291                 return;
292             }
293
294             coap_delete_pdu(pdu);
295         }
296     }
297     else if (SEND_TYPE_MULTICAST == type)
298     {
299         OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
300
301         CAInfo_t *info = &data->requestInfo->info;
302
303         info->options = data->options;
304         info->numOptions = data->numOptions;
305
306         pdu = CAGeneratePDU(CA_GET, info);
307         if (NULL != pdu)
308         {
309             CALogPDUInfo(pdu);
310
311             res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
312             if (CA_STATUS_OK != res)
313             {
314                 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
315                 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
316                 coap_delete_pdu(pdu);
317                 return;
318             }
319
320             coap_delete_pdu(pdu);
321         }
322     }
323
324     OIC_LOG(DEBUG, TAG, "OUT");
325 }
326
327 static void CAReceivedPacketCallback(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen)
328 {
329     OIC_LOG(DEBUG, TAG, "IN");
330     VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
331     VERIFY_NON_NULL_VOID(data, TAG, "data");
332
333     uint32_t code = CA_NOT_FOUND;
334     coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
335     OICFree(data);
336
337     if (NULL == pdu)
338     {
339         OIC_LOG(ERROR, TAG, "Parse PDU failed");
340         return;
341     }
342
343     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
344     {
345         CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
346         if (NULL == ReqInfo)
347         {
348             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
349             coap_delete_pdu(pdu);
350             return;
351         }
352
353         CAResult_t res = CAGetRequestInfoFromPDU(pdu, ReqInfo);
354         if (CA_STATUS_OK != res)
355         {
356             OIC_LOG_V(ERROR, TAG, "CAGetRequestInfoFromPDU failed : %d", res);
357             OICFree(ReqInfo);
358             coap_delete_pdu(pdu);
359             return;
360         }
361
362         if (NULL != ReqInfo->info.options)
363         {
364             uint32_t i;
365             for (i = 0; i < ReqInfo->info.numOptions; i++)
366             {
367                 OIC_LOG_V(DEBUG, TAG, "Request- optionID: %d", ReqInfo->info.options[i].optionID);
368
369                 OIC_LOG_V(DEBUG, TAG, "Request- list: %s", ReqInfo->info.options[i].optionData);
370             }
371         }
372
373         if (NULL != ReqInfo->info.payload)
374         {
375             OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
376         }
377         OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
378         if (NULL != ReqInfo->info.token)
379         {
380             OIC_LOG(DEBUG, TAG, "Request- token:");
381             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token,
382                            ReqInfo->info.tokenLength);
383         }
384
385         OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
386         OIC_LOG(DEBUG, TAG, "Request- token");
387         OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) ReqInfo->info.token, CA_MAX_TOKEN_LEN);
388         OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
389         // store the data at queue.
390         CAData_t *cadata = NULL;
391         cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
392         if (NULL == cadata)
393         {
394             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
395             CADestroyRequestInfoInternal(ReqInfo);
396             coap_delete_pdu(pdu);
397             return;
398         }
399
400         cadata->type = SEND_TYPE_UNICAST;
401         cadata->remoteEndpoint = CAAdapterCloneEndpoint(endpoint);
402         cadata->requestInfo = ReqInfo;
403         cadata->responseInfo = NULL;
404         CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
405     }
406     else
407     {
408         CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
409         if (NULL == ResInfo)
410         {
411             OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
412             coap_delete_pdu(pdu);
413             return;
414         }
415
416         CAResult_t res = CAGetResponseInfoFromPDU(pdu, ResInfo);
417         if (CA_STATUS_OK != res)
418         {
419             OIC_LOG_V(ERROR, TAG, "CAGetResponseInfoFromPDU failed : %d", res);
420             OICFree(ResInfo);
421             coap_delete_pdu(pdu);
422             return;
423         }
424
425         if (NULL != ResInfo->info.options)
426         {
427             uint32_t i;
428             for (i = 0; i < ResInfo->info.numOptions; i++)
429             {
430                 OIC_LOG_V(DEBUG, TAG, "Response- optionID: %d", ResInfo->info.options[i].optionID);
431
432                 OIC_LOG_V(DEBUG, TAG, "Response- list: %s", ResInfo->info.options[i].optionData);
433             }
434         }
435
436         if (NULL != ResInfo->info.payload)
437         {
438             OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
439         }
440         OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
441         OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
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     OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks IN");
497
498 #ifdef SINGLE_HANDLE
499     // parse the data and call the callbacks.
500     // #1 parse the data
501     // #2 get endpoint
502
503     ca_mutex_lock(g_receiveThread.threadMutex);
504
505     u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
506
507     ca_mutex_unlock(g_receiveThread.threadMutex);
508
509     if (NULL == item)
510     {
511         return;
512     }
513
514     // get values
515     void *msg = item->msg;
516
517     if (NULL == msg)
518     {
519         return;
520     }
521
522     // get endpoint
523     CAData_t *td = (CAData_t *) msg;
524
525     if (td->requestInfo && g_requestHandler)
526     {
527         OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
528         g_requestHandler(td->remoteEndpoint, td->requestInfo);
529     }
530     else if (td->responseInfo && g_responseHandler)
531     {
532         OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
533         g_responseHandler(td->remoteEndpoint, td->responseInfo);
534     }
535     else if (td->errorInfo && g_errorHandler)
536     {
537         OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
538         g_errorHandler(td->remoteEndpoint, td->errorInfo);
539     }
540
541     CADataDestroyer(msg, sizeof(CAData_t));
542
543 #endif
544     OIC_LOG(DEBUG, TAG, "CAHandleRequestResponseCallbacks OUT");
545 }
546
547 CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
548 {
549     OIC_LOG(DEBUG, TAG, "IN");
550
551     VERIFY_NON_NULL(object, TAG, "object");
552     VERIFY_NON_NULL(request, TAG, "request");
553
554     if (false == CAIsSelectedNetworkAvailable())
555     {
556         return CA_STATUS_FAILED;
557     }
558
559     CAEndpoint_t *remoteEndpoint = NULL;
560     CARequestInfo_t *requestInfo = NULL;
561     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
562     CA_MEMORY_ALLOC_CHECK(data);
563
564     // clone remote endpoint
565     remoteEndpoint = CACloneEndpoint(object);
566     CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
567
568     // clone request info
569     requestInfo = CACloneRequestInfo(request);
570     CA_MEMORY_ALLOC_CHECK(requestInfo);
571
572     // save data
573     data->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
574     data->remoteEndpoint = remoteEndpoint;
575     data->requestInfo = requestInfo;
576     data->responseInfo = NULL;
577
578     // add thread
579     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
580     OIC_LOG(DEBUG, TAG, "OUT");
581     return CA_STATUS_OK;
582
583 // memory error label.
584 memory_error_exit:
585     CAAdapterFreeEndpoint(remoteEndpoint);
586     CADestroyRequestInfoInternal(requestInfo);
587
588     OICFree(data);
589     OIC_LOG(DEBUG, TAG, "OUT");
590     return CA_MEMORY_ALLOC_FAILED;
591 }
592
593 CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
594                                    const CAResponseInfo_t *response)
595 {
596     OIC_LOG(DEBUG, TAG, "IN");
597     VERIFY_NON_NULL(object, TAG, "object");
598     VERIFY_NON_NULL(response, TAG, "response");
599
600     if (false == CAIsSelectedNetworkAvailable())
601     {
602         return CA_STATUS_FAILED;
603     }
604
605     CAEndpoint_t *remoteEndpoint = NULL;
606     CAResponseInfo_t *responseInfo = NULL;
607
608     // allocate & initialize
609     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
610     CA_MEMORY_ALLOC_CHECK(data);
611
612     // clone remote endpoint
613     remoteEndpoint = CACloneEndpoint(object);
614     CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
615
616     // clone response info
617     responseInfo = CACloneResponseInfo(response);
618     CA_MEMORY_ALLOC_CHECK(responseInfo);
619
620     // save data
621     data->type = SEND_TYPE_UNICAST;
622     data->remoteEndpoint = remoteEndpoint;
623     data->requestInfo = NULL;
624     data->responseInfo = responseInfo;
625
626     // add thread
627     CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
628
629     OIC_LOG(DEBUG, TAG, "OUT");
630     return CA_STATUS_OK;
631
632 // memory error label.
633 memory_error_exit:
634     CAAdapterFreeEndpoint(remoteEndpoint);
635     CADestroyResponseInfoInternal(responseInfo);
636     OICFree(data);
637     OIC_LOG(DEBUG, TAG, "OUT");
638
639     return CA_MEMORY_ALLOC_FAILED;
640 }
641
642 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
643                                       uint8_t tokenLength, const CAHeaderOption_t *options,
644                                       uint8_t numOptions)
645 {
646     return CA_NOT_SUPPORTED;
647 }
648
649 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
650                              CAErrorCallback errroHandler)
651 {
652     OIC_LOG(DEBUG, TAG, "IN");
653     g_requestHandler = ReqHandler;
654     g_responseHandler = RespHandler;
655     g_errorHandler = errroHandler;
656     OIC_LOG(DEBUG, TAG, "OUT");
657 }
658
659 CAResult_t CAInitializeMessageHandler()
660 {
661     OIC_LOG(DEBUG, TAG, "IN");
662     CASetPacketReceivedCallback(CAReceivedPacketCallback);
663
664     CASetNetworkChangeCallback(CANetworkChangedCallback);
665     CASetErrorHandleCallback(CAErrorHandler);
666
667     // create thread pool
668     CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
669
670     if (res != CA_STATUS_OK)
671     {
672         OIC_LOG(ERROR, TAG, "thread pool initialize error.");
673         return res;
674     }
675
676     // send thread initialize
677     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
678                                                    CASendThreadProcess, CADataDestroyer))
679     {
680         OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
681         return CA_STATUS_FAILED;
682     }
683
684     // start send thread
685     res = CAQueueingThreadStart(&g_sendThread);
686
687     if (res != CA_STATUS_OK)
688     {
689         OIC_LOG(ERROR, TAG, "thread start error(send thread).");
690         ca_thread_pool_free(g_threadPoolHandle);
691         g_threadPoolHandle = NULL;
692         return res;
693     }
694
695     // receive thread initialize
696     if (CA_STATUS_OK != CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
697                                                    CAReceiveThreadProcess, CADataDestroyer))
698     {
699         OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
700         return CA_STATUS_FAILED;
701     }
702
703 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
704     // start receive thread
705     res = CAQueueingThreadStart(&gReceiveThread);
706
707     if (res != CA_STATUS_OK)
708     {
709         OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
710         return res;
711     }
712 #endif
713
714     // retransmission initialize
715     CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
716                                CATimeoutCallback, NULL);
717
718     // start retransmission
719     res = CARetransmissionStart(&g_retransmissionContext);
720
721     if (res != CA_STATUS_OK)
722     {
723         OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
724         return res;
725     }
726
727     // initialize interface adapters by controller
728     CAInitializeAdapters(g_threadPoolHandle);
729     OIC_LOG(DEBUG, TAG, "OUT");
730     return CA_STATUS_OK;
731 }
732
733 void CATerminateMessageHandler()
734 {
735     OIC_LOG(DEBUG, TAG, "IN");
736     CATransportAdapter_t connType;
737     u_arraylist_t *list = CAGetSelectedNetworkList();
738     uint32_t length = u_arraylist_length(list);
739
740     uint32_t i = 0;
741     for (i = 0; i < length; i++)
742     {
743         void* ptrType = u_arraylist_get(list, i);
744
745         if (NULL == ptrType)
746         {
747             continue;
748         }
749
750         connType = *(CATransportAdapter_t *)ptrType;
751         CAStopAdapter(connType);
752     }
753
754     // stop retransmission
755     if (NULL != g_retransmissionContext.threadMutex)
756     {
757         CARetransmissionStop(&g_retransmissionContext);
758     }
759
760     // stop thread
761     // delete thread data
762     if (NULL != g_sendThread.threadMutex)
763     {
764         CAQueueingThreadStop(&g_sendThread);
765     }
766
767     // stop thread
768     // delete thread data
769     if (NULL != g_receiveThread.threadMutex)
770     {
771 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
772         CAQueueingThreadStop(&gReceiveThread);
773 #endif
774     }
775
776     // destroy thread pool
777     if (NULL != g_threadPoolHandle)
778     {
779         ca_thread_pool_free(g_threadPoolHandle);
780         g_threadPoolHandle = NULL;
781     }
782
783     CARetransmissionDestroy(&g_retransmissionContext);
784     CAQueueingThreadDestroy(&g_sendThread);
785     CAQueueingThreadDestroy(&g_receiveThread);
786
787     // terminate interface adapters by controller
788     CATerminateAdapters();
789
790     OIC_LOG(DEBUG, TAG, "OUT");
791 }
792
793 void CALogPDUInfo(coap_pdu_t *pdu)
794 {
795     VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
796
797     OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
798
799     OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
800
801     OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
802
803     OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", ntohs(pdu->hdr->id));
804
805     OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
806
807     OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->token, pdu->hdr->token_length);
808 }
809
810 void CAErrorHandler(const CAEndpoint_t *endpoint,
811                     const void *data, uint32_t dataLen,
812                     CAResult_t result)
813 {
814     OIC_LOG(DEBUG, TAG, "IN");
815     VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
816     VERIFY_NON_NULL_VOID(data, TAG, "data");
817
818     uint32_t code = CA_NOT_FOUND;
819     //Do not free remoteEndpoint and data. Currently they will be freed in data thread
820     //Get PDU data
821     coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code);
822     if (NULL == pdu)
823     {
824         OIC_LOG(ERROR, TAG, "Parse PDU failed");
825         return;
826     }
827
828     CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
829     if (NULL == errorInfo)
830     {
831         OIC_LOG(ERROR, TAG, "CAErrorHandler, Memory allocation failed!");
832         coap_delete_pdu(pdu);
833         return;
834     }
835
836     CAResult_t res = CAGetErrorInfoFromPDU(pdu, errorInfo);
837     if (CA_STATUS_OK != res)
838     {
839         OIC_LOG_V(ERROR, TAG, "CAGetErrorInfoFromPDU failed : %d", res);
840         OICFree(errorInfo);
841         coap_delete_pdu(pdu);
842        return;
843     }
844
845     errorInfo->result = result;
846     OIC_LOG_V(DEBUG, TAG, "error : %d", result);
847     if (NULL != errorInfo->info.payload)
848     {
849         OIC_LOG_V(DEBUG, TAG, "error, payload: %s", errorInfo->info.payload);
850     }
851
852     OIC_LOG(DEBUG, TAG, "error, token");
853     OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) errorInfo->info.token,
854                    errorInfo->info.tokenLength);
855     OIC_LOG_V(DEBUG, TAG, "CAErrorHandler, msgID : %d", errorInfo->info.messageId);
856
857     CAEndpoint_t *rep = NULL;
858     rep = CACloneEndpoint(endpoint);
859     if (!rep)
860     {
861         OIC_LOG(ERROR, TAG, "CAErrorHandler, CloneEndpoint Failed");
862         OICFree(errorInfo);
863         coap_delete_pdu(pdu);
864         return;
865     }
866
867     // store the data at queue.
868     CAData_t *cadata = NULL;
869     cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
870     if (NULL == cadata)
871     {
872         OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
873         CADestroyEndpointInternal(rep);
874         OICFree(errorInfo);
875         coap_delete_pdu(pdu);
876         return;
877     }
878
879     cadata->remoteEndpoint = rep;
880     cadata->requestInfo = NULL;
881     cadata->responseInfo = NULL;
882     cadata->errorInfo = errorInfo;
883     cadata->dataType = CA_ERROR_DATA;
884
885     CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
886     coap_delete_pdu(pdu);
887
888     return;
889 }
890