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"
32 #ifndef WITH_UPSTREAM_LIBCOAP
33 #include "coap/config.h"
35 #include "oic_malloc.h"
36 #include "canetworkconfigurator.h"
37 #include "caadapterutils.h"
38 #include "cainterfacecontroller.h"
39 #include "caretransmission.h"
40 #include "oic_string.h"
43 #include "cablockwisetransfer.h"
48 #include "cathreadpool.h" /* for thread pool */
49 #include "caqueueingthread.h"
51 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
52 #include "caconnectionmanager.h"
55 #define MAX_THREAD_POOL_SIZE 20
58 static ca_thread_pool_t g_threadPoolHandle = NULL;
60 // message handler main thread
61 static CAQueueingThread_t g_sendThread;
62 static CAQueueingThread_t g_receiveThread;
65 #define CA_MAX_RT_ARRAY_SIZE 3
66 #endif // SINGLE_THREAD
68 #define TAG "OIC_CA_MSG_HANDLE"
70 static CARetransmission_t g_retransmissionContext;
73 static CARequestCallback g_requestHandler = NULL;
74 static CAResponseCallback g_responseHandler = NULL;
75 static CAErrorCallback g_errorHandler = NULL;
76 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
78 static void CAErrorHandler(const CAEndpoint_t *endpoint,
79 const void *data, size_t dataLen,
82 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
83 const CARemoteId_t *identity,
84 const void *data, CADataType_t dataType);
86 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
90 static void CAProcessReceivedData(CAData_t *data);
92 static void CADestroyData(void *data, uint32_t size);
93 static void CALogPayloadInfo(CAInfo_t *info);
94 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
95 CAToken_t token, uint8_t tokenLength);
98 * print send / receive message of CoAP.
99 * @param[in] data CA information which has send/receive message and endpoint.
100 * @param[in] pdu CoAP pdu low data.
102 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu);
105 void CAAddDataToSendThread(CAData_t *data)
107 VERIFY_NON_NULL_VOID(data, TAG, "data");
110 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
113 void CAAddDataToReceiveThread(CAData_t *data)
115 VERIFY_NON_NULL_VOID(data, TAG, "data");
118 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
122 static bool CAIsSelectedNetworkAvailable()
124 u_arraylist_t *list = CAGetSelectedNetworkList();
125 if (!list || u_arraylist_length(list) == 0)
127 OIC_LOG(ERROR, TAG, "No selected network");
134 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
135 const CARemoteId_t *identity,
136 const void *data, CADataType_t dataType)
138 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
139 CAInfo_t *info = NULL;
140 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
143 OIC_LOG(ERROR, TAG, "memory allocation failed");
147 CAEndpoint_t* ep = endpoint;
149 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
152 OIC_LOG(ERROR, TAG, "endpoint clone failed");
157 OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
159 if (CA_RESPONSE_DATA == dataType)
161 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
164 OIC_LOG(ERROR, TAG, "memory allocation failed");
168 CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
169 if (CA_STATUS_OK != result)
171 OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
172 CADestroyResponseInfoInternal(resInfo);
175 cadata->responseInfo = resInfo;
176 info = &resInfo->info;
179 info->identity = *identity;
181 OIC_LOG(DEBUG, TAG, "Response Info :");
182 CALogPayloadInfo(info);
184 else if (CA_REQUEST_DATA == dataType)
186 CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
189 OIC_LOG(ERROR, TAG, "memory allocation failed");
193 CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
194 if (CA_STATUS_OK != result)
196 OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
197 CADestroyRequestInfoInternal(reqInfo);
201 if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
202 reqInfo->info.token, reqInfo->info.tokenLength))
204 OIC_LOG(INFO, TAG, "Second Request with same Token, Drop it");
205 CADestroyRequestInfoInternal(reqInfo);
209 cadata->requestInfo = reqInfo;
210 info = &reqInfo->info;
213 info->identity = *identity;
215 OIC_LOG(DEBUG, TAG, "Request Info :");
216 CALogPayloadInfo(info);
218 else if (CA_ERROR_DATA == dataType)
220 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
223 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
227 CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
228 if (CA_STATUS_OK != result)
230 OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
235 cadata->errorInfo = errorInfo;
236 info = &errorInfo->info;
239 info->identity = *identity;
241 OIC_LOG(DEBUG, TAG, "error Info :");
242 CALogPayloadInfo(info);
245 cadata->remoteEndpoint = ep;
246 cadata->dataType = dataType;
248 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
253 #ifndef SINGLE_THREAD
259 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
261 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
262 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
264 CAEndpoint_t* ep = endpoint;
266 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
269 OIC_LOG(ERROR, TAG, "clone failed");
274 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
278 OIC_LOG(ERROR, TAG, "calloc failed");
279 #ifndef SINGLE_THREAD
285 resInfo->result = CA_RETRANSMIT_TIMEOUT;
286 resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
287 resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
289 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *) pdu, &(resInfo->info),
291 if (CA_STATUS_OK != res)
293 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
294 CADestroyResponseInfoInternal(resInfo);
295 #ifndef SINGLE_THREAD
301 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
304 OIC_LOG(ERROR, TAG, "memory allocation failed !");
305 #ifndef SINGLE_THREAD
308 CADestroyResponseInfoInternal(resInfo);
312 cadata->type = SEND_TYPE_UNICAST;
313 cadata->remoteEndpoint = ep;
314 cadata->requestInfo = NULL;
315 cadata->responseInfo = resInfo;
318 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
320 res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
321 endpoint->addr, endpoint->port);
322 if (CA_STATUS_OK != res)
324 OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
330 CAProcessReceivedData(cadata);
332 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
336 static void CADestroyData(void *data, uint32_t size)
338 OIC_LOG(DEBUG, TAG, "CADestroyData IN");
339 if ((size_t)size < sizeof(CAData_t))
341 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
343 CAData_t *cadata = (CAData_t *) data;
347 OIC_LOG(ERROR, TAG, "cadata is NULL");
350 #ifndef SINGLE_THREAD
351 if (NULL != cadata->remoteEndpoint)
353 CAFreeEndpoint(cadata->remoteEndpoint);
357 if (NULL != cadata->requestInfo)
359 CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
362 if (NULL != cadata->responseInfo)
364 CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
367 if (NULL != cadata->errorInfo)
369 CADestroyErrorInfoInternal(cadata->errorInfo);
373 OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
377 static void CAProcessReceivedData(CAData_t *data)
379 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
382 OIC_LOG(ERROR, TAG, "thread data error!!");
386 // parse the data and call the callbacks.
389 CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
392 OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
396 if (data->requestInfo && g_requestHandler)
398 g_requestHandler(rep, data->requestInfo);
400 else if (data->responseInfo && g_responseHandler)
402 g_responseHandler(rep, data->responseInfo);
404 else if (data->errorInfo && g_errorHandler)
406 g_errorHandler(rep, data->errorInfo);
409 CADestroyData(data, sizeof(CAData_t));
411 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
415 #ifndef SINGLE_THREAD
416 static void CAReceiveThreadProcess(void *threadData)
418 #ifndef SINGLE_HANDLE
419 CAData_t *data = (CAData_t *) threadData;
420 CAProcessReceivedData(data);
425 #endif // SINGLE_THREAD
427 static CAResult_t CAProcessMulticastData(const CAData_t *data)
429 VERIFY_NON_NULL(data, TAG, "data");
430 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
432 coap_pdu_t *pdu = NULL;
433 CAInfo_t *info = NULL;
434 coap_list_t *options = NULL;
435 coap_transport_t transport = COAP_UDP;
436 CAResult_t res = CA_SEND_FAILED;
438 if (!data->requestInfo && !data->responseInfo)
440 OIC_LOG(ERROR, TAG, "request or response info is empty");
444 if (data->requestInfo)
446 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
448 info = &data->requestInfo->info;
449 pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
451 else if (data->responseInfo)
453 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
455 info = &data->responseInfo->info;
456 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
457 &options, &transport);
462 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
463 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
464 coap_delete_list(options);
469 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
471 // Blockwise transfer
472 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
473 if (CA_STATUS_OK != res)
475 OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
481 CALogPDUInfo(data, pdu);
483 res = CASendMulticastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
484 if (CA_STATUS_OK != res)
486 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
490 coap_delete_list(options);
491 coap_delete_pdu(pdu);
495 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
496 coap_delete_list(options);
497 coap_delete_pdu(pdu);
501 static CAResult_t CAProcessSendData(const CAData_t *data)
503 VERIFY_NON_NULL(data, TAG, "data");
504 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
506 OIC_TRACE_BEGIN(%s:CAProcessSendData, TAG);
508 CAResult_t res = CA_STATUS_FAILED;
510 CASendDataType_t type = data->type;
512 coap_pdu_t *pdu = NULL;
513 CAInfo_t *info = NULL;
514 coap_list_t *options = NULL;
515 coap_transport_t transport = COAP_UDP;
517 if (SEND_TYPE_UNICAST == type)
519 OIC_LOG(DEBUG,TAG,"Unicast message");
521 #ifdef ROUTING_GATEWAY
523 * When forwarding a packet, do not attempt retransmission as its the responsibility of
524 * packet originator node
526 bool skipRetransmission = false;
529 if (NULL != data->requestInfo)
531 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
533 info = &data->requestInfo->info;
534 #ifdef ROUTING_GATEWAY
535 skipRetransmission = data->requestInfo->info.skipRetransmission;
537 pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
538 &options, &transport);
540 else if (NULL != data->responseInfo)
542 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
544 info = &data->responseInfo->info;
545 #ifdef ROUTING_GATEWAY
546 skipRetransmission = data->responseInfo->info.skipRetransmission;
548 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
549 &options, &transport);
553 OIC_LOG(DEBUG, TAG, "request info, response info is empty");
555 return CA_STATUS_INVALID_PARAM;
558 // interface controller function call.
562 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
564 // Blockwise transfer
567 CAResult_t res = CAAddBlockOption(&pdu, info,
568 data->remoteEndpoint,
570 if (CA_STATUS_OK != res)
572 OIC_LOG(INFO, TAG, "to write block option has failed");
573 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
574 coap_delete_list(options);
575 coap_delete_pdu(pdu);
582 CALogPDUInfo(data, pdu);
584 OIC_LOG_V(INFO, TAG, "CASendUnicastData type : %d", data->dataType);
585 res = CASendUnicastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
586 if (CA_STATUS_OK != res)
588 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
589 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
590 coap_delete_list(options);
591 coap_delete_pdu(pdu);
597 if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
599 OIC_LOG(INFO, TAG, "retransmission will be not worked");
603 #ifdef ROUTING_GATEWAY
604 if (!skipRetransmission)
607 // for retransmission
608 res = CARetransmissionSentData(&g_retransmissionContext,
609 data->remoteEndpoint,
611 pdu->transport_hdr, pdu->length);
612 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
614 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
615 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
616 coap_delete_list(options);
617 coap_delete_pdu(pdu);
623 coap_delete_list(options);
624 coap_delete_pdu(pdu);
628 OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
629 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
631 return CA_SEND_FAILED;
634 else if (SEND_TYPE_MULTICAST == type)
636 OIC_LOG(DEBUG,TAG,"Multicast message");
639 * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
640 * That's why we need to generate two pdu's, one for IP and second for other transports.
641 * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
642 * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
644 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
645 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
646 CA_ADAPTER_IP != data->remoteEndpoint->adapter))
648 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
650 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
654 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
656 CAProcessMulticastData(data);
657 data->remoteEndpoint->adapter = CA_ADAPTER_IP;
658 CAProcessMulticastData(data);
662 CAProcessMulticastData(data);
665 CAProcessMulticastData(data);
672 #ifndef SINGLE_THREAD
673 static void CASendThreadProcess(void *threadData)
675 CAData_t *data = (CAData_t *) threadData;
676 CAProcessSendData(data);
681 * If a second message arrives with the same message ID, token and the other address
682 * family, drop it. Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
684 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
685 CAToken_t token, uint8_t tokenLength)
691 if (ep->adapter != CA_ADAPTER_IP)
695 if (!caglobals.ip.dualstack)
700 if (tokenLength > CA_MAX_TOKEN_LEN)
703 * If token length is more than CA_MAX_TOKEN_LEN,
704 * we compare the first CA_MAX_TOKEN_LEN bytes only.
706 tokenLength = CA_MAX_TOKEN_LEN;
710 CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
712 for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
714 CAHistoryItem_t *item = &(history->items[i]);
715 if (id == item->messageId && tokenLength == item->tokenLength
716 && ep->ifindex == item->ifindex && memcmp(item->token, token, tokenLength) == 0)
718 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
719 familyFlags & CA_IPV6 ? '6' : '4');
725 history->items[history->nextIndex].flags = familyFlags;
726 history->items[history->nextIndex].messageId = id;
727 history->items[history->nextIndex].ifindex = ep->ifindex;
728 if (token && tokenLength)
730 memcpy(history->items[history->nextIndex].token, token, tokenLength);
731 history->items[history->nextIndex].tokenLength = tokenLength;
734 if (++history->nextIndex >= HISTORYSIZE)
736 history->nextIndex = 0;
742 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
743 const void *data, size_t dataLen)
745 VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
746 VERIFY_NON_NULL_VOID(data, TAG, "data");
748 OIC_TRACE_BEGIN(%s:CAReceivedPacketCallback, TAG);
752 OIC_LOG(ERROR, TAG, "dataLen is zero");
757 uint32_t code = CA_NOT_FOUND;
758 CAData_t *cadata = NULL;
760 coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
764 OIC_LOG(ERROR, TAG, "Parse PDU failed");
768 OIC_LOG_V(DEBUG, TAG, "code = %d", code);
769 if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
771 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
774 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
775 coap_delete_pdu(pdu);
781 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
784 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
785 coap_delete_pdu(pdu);
790 if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
792 OIC_LOG(INFO, TAG, "retransmission is not supported");
797 // for retransmission
798 void *retransmissionPdu = NULL;
799 CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->transport_hdr,
800 pdu->length, &retransmissionPdu);
802 // get token from saved data in retransmission list
803 if (retransmissionPdu && CA_EMPTY == code)
805 if (cadata->responseInfo)
807 CAInfo_t *info = &cadata->responseInfo->info;
808 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *)retransmissionPdu,
809 info, &(sep->endpoint));
810 if (CA_STATUS_OK != res)
812 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
813 OICFree(info->token);
814 info->tokenLength = 0;
818 OICFree(retransmissionPdu);
822 cadata->type = SEND_TYPE_UNICAST;
824 CALogPDUInfo(cadata, pdu);
827 CAProcessReceivedData(cadata);
830 if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
832 CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
833 if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
835 OIC_LOG(DEBUG, TAG, "this message does not have block option");
836 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
840 CADestroyData(cadata, sizeof(CAData_t));
846 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
848 #endif // SINGLE_THREAD
850 coap_delete_pdu(pdu);
853 OIC_LOG(DEBUG, TAG, "received pdu data :");
854 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLen);
859 void CAHandleRequestResponseCallbacks()
863 CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
866 // parse the data and call the callbacks.
870 oc_mutex_lock(g_receiveThread.threadMutex);
872 u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
874 oc_mutex_unlock(g_receiveThread.threadMutex);
876 if (NULL == item || NULL == item->msg)
882 CAData_t *td = (CAData_t *) item->msg;
884 if (td->requestInfo && g_requestHandler)
886 OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
887 g_requestHandler(td->remoteEndpoint, td->requestInfo);
889 else if (td->responseInfo && g_responseHandler)
891 OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
892 g_responseHandler(td->remoteEndpoint, td->responseInfo);
894 else if (td->errorInfo && g_errorHandler)
896 OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
897 g_errorHandler(td->remoteEndpoint, td->errorInfo);
900 CADestroyData(item->msg, sizeof(CAData_t));
903 #endif // SINGLE_HANDLE
904 #endif // SINGLE_THREAD
907 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
908 CADataType_t dataType)
910 OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
912 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
915 OIC_LOG(ERROR, TAG, "memory allocation failed");
919 if (CA_REQUEST_DATA == dataType)
922 CARequestInfo_t *request = (CARequestInfo_t *)sendData;
924 // clone request info
925 CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
928 OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
932 cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
933 cadata->requestInfo = request;
935 else if (CA_RESPONSE_DATA == dataType || CA_RESPONSE_FOR_RES == dataType)
938 CAResponseInfo_t *response = (CAResponseInfo_t *)sendData;
940 // clone response info
941 CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
944 OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
948 cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
949 cadata->responseInfo = response;
953 OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
958 CAEndpoint_t* ep = endpoint;
960 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
963 OIC_LOG(ERROR, TAG, "endpoint clone failed");
967 cadata->remoteEndpoint = ep;
968 cadata->dataType = dataType;
972 #ifndef SINGLE_THREAD
973 CADestroyData(cadata, sizeof(CAData_t));
980 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
981 CADataType_t dataType)
983 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
984 VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
986 if (false == CAIsSelectedNetworkAvailable())
988 return CA_STATUS_FAILED;
992 // If max retransmission queue is reached, then don't handle new request
993 if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
995 OIC_LOG(ERROR, TAG, "max RT queue size reached!");
996 return CA_SEND_FAILED;
1000 CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
1003 OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
1004 return CA_MEMORY_ALLOC_FAILED;
1007 OIC_LOG_V(DEBUG, TAG, "device ID of endpoint of this message is %s", endpoint->remoteId);
1009 #if defined(TCP_ADAPTER) && defined(WITH_CLOUD)
1010 CAResult_t ret = CACMGetMessageData(data);
1011 if (CA_STATUS_OK != ret)
1013 OIC_LOG(DEBUG, TAG, "Ignore ConnectionManager");
1017 #ifdef SINGLE_THREAD
1018 CAResult_t result = CAProcessSendData(data);
1019 if (CA_STATUS_OK != result)
1021 OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1029 if (SEND_TYPE_UNICAST == data->type && CAIsLocalEndpoint(data->remoteEndpoint))
1032 "This is a loopback message. Transfer it to the receive queue directly");
1033 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
1034 return CA_STATUS_OK;
1037 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
1040 CAResult_t res = CASendBlockWiseData(data);
1041 if (CA_NOT_SUPPORTED == res)
1043 OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1044 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1045 return CA_STATUS_OK;
1049 CADestroyData(data, sizeof(CAData_t));
1056 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1058 #endif // SINGLE_THREAD
1060 return CA_STATUS_OK;
1063 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1064 CAErrorCallback errorHandler)
1066 g_requestHandler = ReqHandler;
1067 g_responseHandler = RespHandler;
1068 g_errorHandler = errorHandler;
1071 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1073 g_nwMonitorHandler = nwMonitorHandler;
1076 CAResult_t CAInitializeMessageHandler(CATransportAdapter_t transportType)
1078 CASetPacketReceivedCallback(CAReceivedPacketCallback);
1079 CASetErrorHandleCallback(CAErrorHandler);
1081 #ifndef SINGLE_THREAD
1082 // create thread pool
1083 CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1084 if (CA_STATUS_OK != res)
1086 OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1090 // send thread initialize
1091 res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1092 CASendThreadProcess, CADestroyData);
1093 if (CA_STATUS_OK != res)
1095 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1099 // start send thread
1100 res = CAQueueingThreadStart(&g_sendThread);
1101 if (CA_STATUS_OK != res)
1103 OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1107 // receive thread initialize
1108 res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1109 CAReceiveThreadProcess, CADestroyData);
1110 if (CA_STATUS_OK != res)
1112 OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1116 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1117 // start receive thread
1118 res = CAQueueingThreadStart(&g_receiveThread);
1119 if (CA_STATUS_OK != res)
1121 OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1124 #endif // SINGLE_HANDLE
1126 // retransmission initialize
1127 res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1128 CASendUnicastData, CATimeoutCallback, NULL);
1129 if (CA_STATUS_OK != res)
1131 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1136 // block-wise transfer initialize
1137 res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1138 if (CA_STATUS_OK != res)
1140 OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1145 // start retransmission
1146 res = CARetransmissionStart(&g_retransmissionContext);
1147 if (CA_STATUS_OK != res)
1149 OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1153 // initialize interface adapters by controller
1154 CAInitializeAdapters(g_threadPoolHandle, transportType);
1156 // retransmission initialize
1157 CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1158 CATimeoutCallback, NULL);
1159 if (CA_STATUS_OK != res)
1161 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1165 CAInitializeAdapters();
1166 #endif // SINGLE_THREAD
1168 return CA_STATUS_OK;
1171 void CATerminateMessageHandler()
1173 #ifndef SINGLE_THREAD
1174 CATransportAdapter_t connType;
1175 u_arraylist_t *list = CAGetSelectedNetworkList();
1176 size_t length = u_arraylist_length(list);
1178 for (size_t i = 0; i < length; i++)
1180 void* ptrType = u_arraylist_get(list, i);
1182 if (NULL == ptrType)
1187 connType = *(CATransportAdapter_t *)ptrType;
1188 CAStopAdapter(connType);
1191 // stop retransmission
1192 if (NULL != g_retransmissionContext.threadMutex)
1194 CARetransmissionStop(&g_retransmissionContext);
1198 // delete thread data
1199 if (NULL != g_sendThread.threadMutex)
1201 CAQueueingThreadStop(&g_sendThread);
1205 // delete thread data
1206 if (NULL != g_receiveThread.threadMutex)
1208 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1209 CAQueueingThreadStop(&g_receiveThread);
1213 // destroy thread pool
1214 if (NULL != g_threadPoolHandle)
1216 ca_thread_pool_free(g_threadPoolHandle);
1217 g_threadPoolHandle = NULL;
1221 CATerminateBlockWiseTransfer();
1223 CARetransmissionDestroy(&g_retransmissionContext);
1224 CAQueueingThreadDestroy(&g_sendThread);
1225 CAQueueingThreadDestroy(&g_receiveThread);
1227 // terminate interface adapters by controller
1228 CATerminateAdapters();
1230 // terminate interface adapters by controller
1231 CATerminateAdapters();
1233 // stop retransmission
1234 CARetransmissionStop(&g_retransmissionContext);
1235 CARetransmissionDestroy(&g_retransmissionContext);
1236 #endif // SINGLE_THREAD
1239 static void CALogPayloadInfo(CAInfo_t *info)
1245 for (uint32_t i = 0; i < info->numOptions; i++)
1247 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1249 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1255 OIC_LOG_V(DEBUG, TAG, "payload: %p(%" PRIuPTR ")", info->payload,
1261 OIC_LOG(DEBUG, TAG, "token:");
1262 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1265 OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1269 OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1273 void CAErrorHandler(const CAEndpoint_t *endpoint,
1274 const void *data, size_t dataLen,
1277 OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1278 VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1279 VERIFY_NON_NULL_VOID(data, TAG, "data");
1283 OIC_LOG(ERROR, TAG, "dataLen is zero");
1287 #ifndef SINGLE_THREAD
1288 uint32_t code = CA_NOT_FOUND;
1289 //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1291 coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1294 OIC_LOG(ERROR, TAG, "Parse PDU failed");
1298 CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1301 OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1302 coap_delete_pdu(pdu);
1306 cadata->errorInfo->result = result;
1308 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1309 coap_delete_pdu(pdu);
1314 OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1318 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1320 OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1321 #ifndef SINGLE_THREAD
1322 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1325 OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1329 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1332 OIC_LOG(ERROR, TAG, "endpoint clone failed");
1337 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1340 OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1346 CAResult_t res = CACloneInfo(info, &errorInfo->info);
1347 if (CA_STATUS_OK != res)
1349 OIC_LOG(ERROR, TAG, "info clone failed");
1356 errorInfo->result = result;
1357 cadata->remoteEndpoint = ep;
1358 cadata->errorInfo = errorInfo;
1359 cadata->dataType = CA_ERROR_DATA;
1361 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1363 OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1367 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1369 OIC_LOG(DEBUG, TAG, "CALogPDUInfo");
1371 VERIFY_NON_NULL_VOID(data, TAG, "data");
1372 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1374 OIC_LOG(DEBUG, ANALYZER_TAG, "=================================================");
1375 if(SEND_TYPE_MULTICAST == data->type)
1377 OIC_LOG(DEBUG, ANALYZER_TAG, "Is Multicast = true");
1381 OIC_LOG(DEBUG, ANALYZER_TAG, "Is Multicast = false");
1384 if (NULL != data->remoteEndpoint)
1386 CALogAdapterTypeInfo(data->remoteEndpoint->adapter);
1387 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Address = [%s]:[%d]", data->remoteEndpoint->addr,
1388 data->remoteEndpoint->port);
1391 switch(data->dataType)
1393 case CA_REQUEST_DATA:
1394 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_REQUEST_DATA]");
1396 case CA_RESPONSE_DATA:
1397 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_RESPONSE_DATA]");
1400 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_ERROR_DATA]");
1402 case CA_RESPONSE_FOR_RES:
1403 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_RESPONSE_FOR_RES]");
1406 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Data Type = [%d]", data->dataType);
1409 OIC_LOG(DEBUG, ANALYZER_TAG, "-------------------------------------------------");
1411 const CAInfo_t *info = NULL;
1412 if (NULL != data->requestInfo)
1414 switch(data->requestInfo->method)
1417 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [GET]");
1420 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [POST]");
1423 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [PUT]");
1426 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [DELETE]");
1429 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Method = [%d]", data->requestInfo->method);
1432 info = &data->requestInfo->info;
1435 if (NULL != data->responseInfo)
1437 OIC_LOG_V(DEBUG, ANALYZER_TAG, "result code = [%d]", data->responseInfo->result);
1438 info = &data->responseInfo->info;
1441 if (pdu->transport_hdr)
1443 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Msg ID = [%u]",
1444 (uint32_t)ntohs(pdu->transport_hdr->udp.id));
1449 OIC_LOG(DEBUG, ANALYZER_TAG, "Coap Token");
1450 OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, (const uint8_t *) info->token, info->tokenLength);
1451 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Res URI = [%s]", info->resourceUri);
1453 if (CA_FORMAT_APPLICATION_CBOR == info->payloadFormat)
1455 OIC_LOG(DEBUG, ANALYZER_TAG, "Payload Format = [CA_FORMAT_APPLICATION_CBOR]");
1459 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Payload Format = [%d]", info->payloadFormat);
1463 size_t payloadLen = (pdu->data) ? (unsigned char *) pdu->hdr + pdu->length - pdu->data : 0;
1464 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Message Full Size = [%lu]", pdu->length);
1465 OIC_LOG(DEBUG, ANALYZER_TAG, "CoAP Header (+ 0xFF)");
1466 OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, (const uint8_t *) pdu->transport_hdr,
1467 pdu->length - payloadLen);
1468 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Header size = [%lu]", pdu->length - payloadLen);
1470 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload");
1471 // OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, pdu->data, payloadLen);
1472 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload Size = [%lu]", payloadLen);
1473 OIC_LOG(DEBUG, ANALYZER_TAG, "=================================================");
1476 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1478 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1481 OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1482 OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->transport_hdr->udp.type);
1483 OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->transport_hdr->udp.code);
1484 OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1485 OIC_LOG_BUFFER(DEBUG, TAG, pdu->transport_hdr->udp.token,
1486 pdu->transport_hdr->udp.token_length);