1 /* *****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
26 #include "cainterface.h"
27 #include "camessagehandler.h"
28 #include "caremotehandler.h"
29 #include "caprotocolmessage.h"
31 #include "config.h" /* for coap protocol */
32 #include "oic_malloc.h"
33 #include "canetworkconfigurator.h"
34 #include "caadapterutils.h"
35 #include "cainterfacecontroller.h"
36 #include "caretransmission.h"
37 #include "oic_string.h"
40 #include "cablockwisetransfer.h"
45 #include "cathreadpool.h" /* for thread pool */
46 #include "caqueueingthread.h"
49 #define MAX_THREAD_POOL_SIZE 20
52 static ca_thread_pool_t g_threadPoolHandle = NULL;
54 // message handler main thread
55 static CAQueueingThread_t g_sendThread;
56 static CAQueueingThread_t g_receiveThread;
59 #define CA_MAX_RT_ARRAY_SIZE 3
60 #endif // SINGLE_THREAD
62 #define TAG "OIC_CA_MSG_HANDLE"
64 static CARetransmission_t g_retransmissionContext;
67 static CARequestCallback g_requestHandler = NULL;
68 static CAResponseCallback g_responseHandler = NULL;
69 static CAErrorCallback g_errorHandler = NULL;
70 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
72 static void CAErrorHandler(const CAEndpoint_t *endpoint,
73 const void *data, uint32_t dataLen,
76 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
77 const CARemoteId_t *identity,
78 const void *data, CADataType_t dataType);
80 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
84 static void CAProcessReceivedData(CAData_t *data);
86 static void CADestroyData(void *data, uint32_t size);
87 static void CALogPayloadInfo(CAInfo_t *info);
88 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
89 CAToken_t token, uint8_t tokenLength);
92 void CAAddDataToSendThread(CAData_t *data)
94 VERIFY_NON_NULL_VOID(data, TAG, "data");
97 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
100 void CAAddDataToReceiveThread(CAData_t *data)
102 VERIFY_NON_NULL_VOID(data, TAG, "data");
105 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
109 static bool CAIsSelectedNetworkAvailable()
111 u_arraylist_t *list = CAGetSelectedNetworkList();
112 if (!list || u_arraylist_length(list) == 0)
114 OIC_LOG(ERROR, TAG, "No selected network");
121 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
122 const CARemoteId_t *identity,
123 const void *data, CADataType_t dataType)
125 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
126 CAInfo_t *info = NULL;
127 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
130 OIC_LOG(ERROR, TAG, "memory allocation failed");
134 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
137 OIC_LOG(ERROR, TAG, "endpoint clone failed");
141 OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
143 if (CA_RESPONSE_DATA == dataType)
145 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
148 OIC_LOG(ERROR, TAG, "memory allocation failed");
152 CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
153 if (CA_STATUS_OK != result)
155 OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
156 CADestroyResponseInfoInternal(resInfo);
159 cadata->responseInfo = resInfo;
160 info = &resInfo->info;
163 info->identity = *identity;
165 OIC_LOG(DEBUG, TAG, "Response Info :");
166 CALogPayloadInfo(info);
168 else if (CA_REQUEST_DATA == dataType)
170 CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
173 OIC_LOG(ERROR, TAG, "memory allocation failed");
177 CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
178 if (CA_STATUS_OK != result)
180 OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
181 CADestroyRequestInfoInternal(reqInfo);
185 if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
186 reqInfo->info.token, reqInfo->info.tokenLength))
188 OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
189 CADestroyRequestInfoInternal(reqInfo);
193 cadata->requestInfo = reqInfo;
194 info = &reqInfo->info;
197 info->identity = *identity;
199 OIC_LOG(DEBUG, TAG, "Request Info :");
200 CALogPayloadInfo(info);
202 else if (CA_ERROR_DATA == dataType)
204 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
207 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
211 CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
212 if (CA_STATUS_OK != result)
214 OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
219 cadata->errorInfo = errorInfo;
220 info = &errorInfo->info;
223 info->identity = *identity;
225 OIC_LOG(DEBUG, TAG, "error Info :");
226 CALogPayloadInfo(info);
229 cadata->remoteEndpoint = ep;
230 cadata->dataType = dataType;
232 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
241 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
243 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
244 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
246 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
249 OIC_LOG(ERROR, TAG, "clone failed");
253 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
257 OIC_LOG(ERROR, TAG, "calloc failed");
262 resInfo->result = CA_RETRANSMIT_TIMEOUT;
263 resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
264 resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
266 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
268 if (CA_STATUS_OK != res)
270 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
271 CADestroyResponseInfoInternal(resInfo);
276 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
279 OIC_LOG(ERROR, TAG, "memory allocation failed !");
281 CADestroyResponseInfoInternal(resInfo);
285 cadata->type = SEND_TYPE_UNICAST;
286 cadata->remoteEndpoint = ep;
287 cadata->requestInfo = NULL;
288 cadata->responseInfo = resInfo;
291 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
293 res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
295 if (CA_STATUS_OK != res)
297 OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
303 CAProcessReceivedData(cadata);
305 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
309 static void CADestroyData(void *data, uint32_t size)
311 OIC_LOG(DEBUG, TAG, "CADestroyData IN");
312 if ((size_t)size < sizeof(CAData_t))
314 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
316 CAData_t *cadata = (CAData_t *) data;
320 OIC_LOG(ERROR, TAG, "cadata is NULL");
324 if (NULL != cadata->remoteEndpoint)
326 CAFreeEndpoint(cadata->remoteEndpoint);
329 if (NULL != cadata->requestInfo)
331 CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
334 if (NULL != cadata->responseInfo)
336 CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
339 if (NULL != cadata->errorInfo)
341 CADestroyErrorInfoInternal(cadata->errorInfo);
345 OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
349 static void CAProcessReceivedData(CAData_t *data)
351 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
354 OIC_LOG(ERROR, TAG, "thread data error!!");
358 // parse the data and call the callbacks.
361 CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
364 OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
368 if (data->requestInfo && g_requestHandler)
370 g_requestHandler(rep, data->requestInfo);
372 else if (data->responseInfo && g_responseHandler)
374 g_responseHandler(rep, data->responseInfo);
376 else if (data->errorInfo && g_errorHandler)
378 g_errorHandler(rep, data->errorInfo);
381 CADestroyData(data, sizeof(CAData_t));
383 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
387 #ifndef SINGLE_THREAD
388 static void CAReceiveThreadProcess(void *threadData)
390 #ifndef SINGLE_HANDLE
391 CAData_t *data = (CAData_t *) threadData;
392 CAProcessReceivedData(data);
397 #endif // SINGLE_THREAD
399 static CAResult_t CAProcessMulticastData(const CAData_t *data)
401 VERIFY_NON_NULL(data, TAG, "data");
402 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
404 coap_pdu_t *pdu = NULL;
405 CAInfo_t *info = NULL;
406 coap_list_t *options = NULL;
407 coap_transport_type transport = coap_udp;
408 CAResult_t res = CA_SEND_FAILED;
410 if (!data->requestInfo && !data->responseInfo)
412 OIC_LOG(ERROR, TAG, "request or response info is empty");
416 if (data->requestInfo)
418 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
420 info = &data->requestInfo->info;
421 pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
423 else if (data->responseInfo)
425 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
427 info = &data->responseInfo->info;
428 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
429 &options, &transport);
434 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
435 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
436 coap_delete_list(options);
441 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
443 // Blockwise transfer
444 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
445 if (CA_STATUS_OK != res)
447 OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
453 CALogPDUInfo(pdu, data->remoteEndpoint);
455 OIC_LOG(DEBUG, TAG, "pdu to send :");
456 OIC_LOG_BUFFER(DEBUG, TAG, (uint8_t*)pdu->hdr, pdu->length);
458 res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length, data->dataType);
459 if (CA_STATUS_OK != res)
461 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
465 coap_delete_list(options);
466 coap_delete_pdu(pdu);
470 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
471 coap_delete_list(options);
472 coap_delete_pdu(pdu);
476 static CAResult_t CAProcessSendData(const CAData_t *data)
478 VERIFY_NON_NULL(data, TAG, "data");
479 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
481 CAResult_t res = CA_STATUS_FAILED;
483 CASendDataType_t type = data->type;
485 coap_pdu_t *pdu = NULL;
486 CAInfo_t *info = NULL;
487 coap_list_t *options = NULL;
488 coap_transport_type transport = coap_udp;
490 if (SEND_TYPE_UNICAST == type)
492 OIC_LOG(DEBUG,TAG,"Unicast message");
494 #ifdef ROUTING_GATEWAY
496 * When forwarding a packet, do not attempt retransmission as its the responsibility of
497 * packet originator node
499 bool skipRetransmission = false;
502 if (NULL != data->requestInfo)
504 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
506 info = &data->requestInfo->info;
507 #ifdef ROUTING_GATEWAY
508 skipRetransmission = data->requestInfo->info.skipRetransmission;
510 pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
511 &options, &transport);
513 else if (NULL != data->responseInfo)
515 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
517 info = &data->responseInfo->info;
518 #ifdef ROUTING_GATEWAY
519 skipRetransmission = data->responseInfo->info.skipRetransmission;
521 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
522 &options, &transport);
526 OIC_LOG(DEBUG, TAG, "request info, response info is empty");
527 return CA_STATUS_INVALID_PARAM;
530 // interface controller function call.
534 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
536 // Blockwise transfer
539 CAResult_t res = CAAddBlockOption(&pdu, info,
540 data->remoteEndpoint,
542 if (CA_STATUS_OK != res)
544 OIC_LOG(INFO, TAG, "to write block option has failed");
545 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
546 coap_delete_list(options);
547 coap_delete_pdu(pdu);
553 CALogPDUInfo(pdu, data->remoteEndpoint);
555 OIC_LOG_V(INFO, TAG, "CASendUnicastData type : %d", data->dataType);
556 res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length, data->dataType);
557 if (CA_STATUS_OK != res)
559 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
560 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
561 coap_delete_list(options);
562 coap_delete_pdu(pdu);
567 if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
569 OIC_LOG(INFO, TAG, "retransmission will be not worked");
573 #ifdef ROUTING_GATEWAY
574 if(!skipRetransmission)
577 // for retransmission
578 res = CARetransmissionSentData(&g_retransmissionContext,
579 data->remoteEndpoint,
581 pdu->hdr, pdu->length);
582 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
584 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
585 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
586 coap_delete_list(options);
587 coap_delete_pdu(pdu);
592 coap_delete_list(options);
593 coap_delete_pdu(pdu);
597 OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
598 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
599 return CA_SEND_FAILED;
602 else if (SEND_TYPE_MULTICAST == type)
604 OIC_LOG(DEBUG,TAG,"Multicast message");
607 * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
608 * That's why we need to generate two pdu's, one for IP and second for other transports.
609 * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
610 * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
612 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
613 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
614 CA_ADAPTER_IP != data->remoteEndpoint->adapter))
616 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
618 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
622 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
624 CAProcessMulticastData(data);
625 data->remoteEndpoint->adapter = CA_ADAPTER_IP;
626 CAProcessMulticastData(data);
630 CAProcessMulticastData(data);
633 CAProcessMulticastData(data);
640 #ifndef SINGLE_THREAD
641 static void CASendThreadProcess(void *threadData)
643 CAData_t *data = (CAData_t *) threadData;
644 CAProcessSendData(data);
649 * If a second message arrives with the same message ID, token and the other address
650 * family, drop it. Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
652 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
653 CAToken_t token, uint8_t tokenLength)
659 if (ep->adapter != CA_ADAPTER_IP)
663 if (!caglobals.ip.dualstack)
668 if (tokenLength > CA_MAX_TOKEN_LEN)
671 * If token length is more than CA_MAX_TOKEN_LEN,
672 * we compare the first CA_MAX_TOKEN_LEN bytes only.
674 tokenLength = CA_MAX_TOKEN_LEN;
678 CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
680 for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
682 CAHistoryItem_t *item = &(history->items[i]);
683 if (id == item->messageId && tokenLength == item->tokenLength
684 && memcmp(item->token, token, tokenLength) == 0)
686 if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
688 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
689 familyFlags & CA_IPV6 ? '6' : '4');
696 history->items[history->nextIndex].flags = familyFlags;
697 history->items[history->nextIndex].messageId = id;
698 if (token && tokenLength)
700 memcpy(history->items[history->nextIndex].token, token, tokenLength);
701 history->items[history->nextIndex].tokenLength = tokenLength;
704 if (++history->nextIndex >= HISTORYSIZE)
706 history->nextIndex = 0;
712 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
713 const void *data, uint32_t dataLen)
715 VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
716 VERIFY_NON_NULL_VOID(data, TAG, "data");
718 OIC_LOG(DEBUG, TAG, "received pdu data :");
719 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLen);
721 uint32_t code = CA_NOT_FOUND;
722 CAData_t *cadata = NULL;
724 coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
728 OIC_LOG(ERROR, TAG, "Parse PDU failed");
732 OIC_LOG_V(DEBUG, TAG, "code = %d", code);
733 if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
735 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
738 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
739 coap_delete_pdu(pdu);
745 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
748 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
749 coap_delete_pdu(pdu);
754 if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
756 OIC_LOG(INFO, TAG, "retransmission is not supported");
761 // for retransmission
762 void *retransmissionPdu = NULL;
763 CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
764 pdu->length, &retransmissionPdu);
766 // get token from saved data in retransmission list
767 if (retransmissionPdu && CA_EMPTY == code)
769 if (cadata->responseInfo)
771 CAInfo_t *info = &cadata->responseInfo->info;
772 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
773 info, &(sep->endpoint));
774 if (CA_STATUS_OK != res)
776 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
777 OICFree(info->token);
778 info->tokenLength = 0;
782 OICFree(retransmissionPdu);
786 cadata->type = SEND_TYPE_UNICAST;
789 CAProcessReceivedData(cadata);
792 if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
794 CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
795 if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
797 OIC_LOG(DEBUG, TAG, "this message does not have block option");
798 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
802 CADestroyData(cadata, sizeof(CAData_t));
808 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
810 #endif // SINGLE_THREAD
812 coap_delete_pdu(pdu);
815 void CAHandleRequestResponseCallbacks()
819 CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
822 // parse the data and call the callbacks.
826 ca_mutex_lock(g_receiveThread.threadMutex);
828 u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
830 ca_mutex_unlock(g_receiveThread.threadMutex);
832 if (NULL == item || NULL == item->msg)
838 CAData_t *td = (CAData_t *) item->msg;
840 if (td->requestInfo && g_requestHandler)
842 OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
843 g_requestHandler(td->remoteEndpoint, td->requestInfo);
845 else if (td->responseInfo && g_responseHandler)
847 OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
848 g_responseHandler(td->remoteEndpoint, td->responseInfo);
850 else if (td->errorInfo && g_errorHandler)
852 OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
853 g_errorHandler(td->remoteEndpoint, td->errorInfo);
856 CADestroyData(item->msg, sizeof(CAData_t));
859 #endif // SINGLE_HANDLE
860 #endif // SINGLE_THREAD
863 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
864 CADataType_t dataType)
866 OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
868 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
871 OIC_LOG(ERROR, TAG, "memory allocation failed");
875 if (CA_REQUEST_DATA == dataType)
877 // clone request info
878 CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
882 OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
886 cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
887 cadata->requestInfo = request;
889 else if (CA_RESPONSE_DATA == dataType || CA_RESPONSE_FOR_RES == dataType)
891 // clone response info
892 CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
896 OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
900 cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
901 cadata->responseInfo = response;
905 OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
909 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
912 OIC_LOG(ERROR, TAG, "endpoint clone failed");
916 cadata->remoteEndpoint = ep;
917 cadata->dataType = dataType;
921 CADestroyData(cadata, sizeof(CAData_t));
925 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
926 CADataType_t dataType)
928 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
929 VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
931 if (false == CAIsSelectedNetworkAvailable())
933 return CA_STATUS_FAILED;
937 // If max retransmission queue is reached, then don't handle new request
938 if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
940 OIC_LOG(ERROR, TAG, "max RT queue size reached!");
941 return CA_SEND_FAILED;
945 CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
948 OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
949 return CA_MEMORY_ALLOC_FAILED;
953 CAResult_t result = CAProcessSendData(data);
954 if (CA_STATUS_OK != result)
956 OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
957 CADestroyData(data, sizeof(CAData_t));
961 CADestroyData(data, sizeof(CAData_t));
964 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
967 CAResult_t res = CASendBlockWiseData(data);
968 if (CA_NOT_SUPPORTED == res)
970 OIC_LOG(DEBUG, TAG, "normal msg will be sent");
971 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
976 CADestroyData(data, sizeof(CAData_t));
983 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
985 #endif // SINGLE_THREAD
990 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
991 CAErrorCallback errorHandler)
993 g_requestHandler = ReqHandler;
994 g_responseHandler = RespHandler;
995 g_errorHandler = errorHandler;
998 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1000 g_nwMonitorHandler = nwMonitorHandler;
1003 CAResult_t CAInitializeMessageHandler()
1005 CASetPacketReceivedCallback(CAReceivedPacketCallback);
1006 CASetErrorHandleCallback(CAErrorHandler);
1008 #ifndef SINGLE_THREAD
1009 // create thread pool
1010 CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1011 if (CA_STATUS_OK != res)
1013 OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1017 // send thread initialize
1018 res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1019 CASendThreadProcess, CADestroyData);
1020 if (CA_STATUS_OK != res)
1022 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1023 ca_thread_pool_free(g_threadPoolHandle);
1024 g_threadPoolHandle = NULL;
1028 // start send thread
1029 res = CAQueueingThreadStart(&g_sendThread);
1030 if (CA_STATUS_OK != res)
1032 OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1033 ca_thread_pool_free(g_threadPoolHandle);
1034 g_threadPoolHandle = NULL;
1035 CAQueueingThreadDestroy(&g_sendThread);
1039 // receive thread initialize
1040 res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1041 CAReceiveThreadProcess, CADestroyData);
1042 if (CA_STATUS_OK != res)
1044 OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1045 ca_thread_pool_free(g_threadPoolHandle);
1046 g_threadPoolHandle = NULL;
1047 CAQueueingThreadDestroy(&g_sendThread);
1051 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1052 // start receive thread
1053 res = CAQueueingThreadStart(&g_receiveThread);
1054 if (CA_STATUS_OK != res)
1056 OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1057 ca_thread_pool_free(g_threadPoolHandle);
1058 g_threadPoolHandle = NULL;
1059 CAQueueingThreadDestroy(&g_sendThread);
1060 CAQueueingThreadDestroy(&g_receiveThread);
1063 #endif // SINGLE_HANDLE
1065 // retransmission initialize
1066 res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1067 CASendUnicastData, CATimeoutCallback, NULL);
1068 if (CA_STATUS_OK != res)
1070 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1071 ca_thread_pool_free(g_threadPoolHandle);
1072 g_threadPoolHandle = NULL;
1073 CAQueueingThreadDestroy(&g_sendThread);
1074 CAQueueingThreadDestroy(&g_receiveThread);
1079 // block-wise transfer initialize
1080 res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1081 if (CA_STATUS_OK != res)
1083 OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1084 ca_thread_pool_free(g_threadPoolHandle);
1085 g_threadPoolHandle = NULL;
1086 CAQueueingThreadDestroy(&g_sendThread);
1087 CAQueueingThreadDestroy(&g_receiveThread);
1088 CARetransmissionDestroy(&g_retransmissionContext);
1093 // start retransmission
1094 res = CARetransmissionStart(&g_retransmissionContext);
1095 if (CA_STATUS_OK != res)
1097 OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1098 ca_thread_pool_free(g_threadPoolHandle);
1099 g_threadPoolHandle = NULL;
1100 CAQueueingThreadDestroy(&g_sendThread);
1101 CAQueueingThreadDestroy(&g_receiveThread);
1102 CARetransmissionDestroy(&g_retransmissionContext);
1106 // initialize interface adapters by controller
1107 CAInitializeAdapters(g_threadPoolHandle);
1109 // retransmission initialize
1110 CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1111 CATimeoutCallback, NULL);
1112 if (CA_STATUS_OK != res)
1114 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1118 CAInitializeAdapters();
1119 #endif // SINGLE_THREAD
1121 return CA_STATUS_OK;
1124 void CATerminateMessageHandler()
1126 #ifndef SINGLE_THREAD
1127 CATransportAdapter_t connType;
1128 u_arraylist_t *list = CAGetSelectedNetworkList();
1129 uint32_t length = u_arraylist_length(list);
1132 for (i = 0; i < length; i++)
1134 void* ptrType = u_arraylist_get(list, i);
1136 if (NULL == ptrType)
1141 connType = *(CATransportAdapter_t *)ptrType;
1142 CAStopAdapter(connType);
1145 // stop retransmission
1146 if (NULL != g_retransmissionContext.threadMutex)
1148 CARetransmissionStop(&g_retransmissionContext);
1152 // delete thread data
1153 if (NULL != g_sendThread.threadMutex)
1155 CAQueueingThreadStop(&g_sendThread);
1159 // delete thread data
1160 if (NULL != g_receiveThread.threadMutex)
1162 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1163 CAQueueingThreadStop(&g_receiveThread);
1167 // destroy thread pool
1168 if (NULL != g_threadPoolHandle)
1170 ca_thread_pool_free(g_threadPoolHandle);
1171 g_threadPoolHandle = NULL;
1175 CATerminateBlockWiseTransfer();
1177 CARetransmissionDestroy(&g_retransmissionContext);
1178 CAQueueingThreadDestroy(&g_sendThread);
1179 CAQueueingThreadDestroy(&g_receiveThread);
1181 // terminate interface adapters by controller
1182 CATerminateAdapters();
1184 // terminate interface adapters by controller
1185 CATerminateAdapters();
1187 // stop retransmission
1188 CARetransmissionStop(&g_retransmissionContext);
1189 CARetransmissionDestroy(&g_retransmissionContext);
1190 #endif // SINGLE_THREAD
1193 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1195 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1196 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1198 OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1201 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1203 OIC_LOG(DEBUG, TAG, "pdu header data :");
1204 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) pdu->hdr, pdu->length);
1209 OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1211 OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1213 OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1215 OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1216 pdu->hdr->coap_hdr_udp_t.token_length);
1220 static void CALogPayloadInfo(CAInfo_t *info)
1226 for (uint32_t i = 0; i < info->numOptions; i++)
1228 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1230 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1236 OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1242 OIC_LOG(DEBUG, TAG, "token:");
1243 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1246 OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1250 OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1254 void CAErrorHandler(const CAEndpoint_t *endpoint,
1255 const void *data, uint32_t dataLen,
1258 OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1260 #ifndef SINGLE_THREAD
1261 VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1262 VERIFY_NON_NULL_VOID(data, TAG, "data");
1264 uint32_t code = CA_NOT_FOUND;
1265 //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1267 coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1270 OIC_LOG(ERROR, TAG, "Parse PDU failed");
1274 CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1277 OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1278 coap_delete_pdu(pdu);
1282 cadata->errorInfo->result = result;
1284 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1285 coap_delete_pdu(pdu);
1288 OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1292 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1294 OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1295 #ifndef SINGLE_THREAD
1296 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1299 OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1303 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1306 OIC_LOG(ERROR, TAG, "endpoint clone failed");
1311 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1314 OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1320 CAResult_t res = CACloneInfo(info, &errorInfo->info);
1321 if (CA_STATUS_OK != res)
1323 OIC_LOG(ERROR, TAG, "info clone failed");
1330 errorInfo->result = result;
1331 cadata->remoteEndpoint = ep;
1332 cadata->errorInfo = errorInfo;
1333 cadata->dataType = CA_ERROR_DATA;
1335 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1337 OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");