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 #ifndef WITH_UPSTREAM_LIBCOAP
32 #include "coap/config.h"
34 #include "oic_malloc.h"
35 #include "canetworkconfigurator.h"
36 #include "caadapterutils.h"
37 #include "cainterfacecontroller.h"
38 #include "caretransmission.h"
39 #include "oic_string.h"
42 #include "cablockwisetransfer.h"
47 #include "cathreadpool.h" /* for thread pool */
48 #include "caqueueingthread.h"
51 #define MAX_THREAD_POOL_SIZE 20
54 static ca_thread_pool_t g_threadPoolHandle = NULL;
56 // message handler main thread
57 static CAQueueingThread_t g_sendThread;
58 static CAQueueingThread_t g_receiveThread;
61 #define CA_MAX_RT_ARRAY_SIZE 3
62 #endif // SINGLE_THREAD
64 #define TAG "OIC_CA_MSG_HANDLE"
66 static CARetransmission_t g_retransmissionContext;
69 static CARequestCallback g_requestHandler = NULL;
70 static CAResponseCallback g_responseHandler = NULL;
71 static CAErrorCallback g_errorHandler = NULL;
72 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
74 static void CAErrorHandler(const CAEndpoint_t *endpoint,
75 const void *data, size_t dataLen,
78 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
79 const CARemoteId_t *identity,
80 const void *data, CADataType_t dataType);
82 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
86 static void CAProcessReceivedData(CAData_t *data);
88 static void CADestroyData(void *data, uint32_t size);
89 static void CALogPayloadInfo(CAInfo_t *info);
90 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
91 CAToken_t token, uint8_t tokenLength);
94 * print send / receive message of CoAP.
95 * @param[in] data CA information which has send/receive message and endpoint.
96 * @param[in] pdu CoAP pdu low data.
98 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu);
101 void CAAddDataToSendThread(CAData_t *data)
103 VERIFY_NON_NULL_VOID(data, TAG, "data");
106 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
109 void CAAddDataToReceiveThread(CAData_t *data)
111 VERIFY_NON_NULL_VOID(data, TAG, "data");
114 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
118 static bool CAIsSelectedNetworkAvailable()
120 u_arraylist_t *list = CAGetSelectedNetworkList();
121 if (!list || u_arraylist_length(list) == 0)
123 OIC_LOG(ERROR, TAG, "No selected network");
130 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
131 const CARemoteId_t *identity,
132 const void *data, CADataType_t dataType)
134 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
135 CAInfo_t *info = NULL;
136 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
139 OIC_LOG(ERROR, TAG, "memory allocation failed");
143 CAEndpoint_t* ep = endpoint;
145 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
148 OIC_LOG(ERROR, TAG, "endpoint clone failed");
153 OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
155 if (CA_RESPONSE_DATA == dataType)
157 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
160 OIC_LOG(ERROR, TAG, "memory allocation failed");
164 CAResult_t result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
165 if (CA_STATUS_OK != result)
167 OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
168 CADestroyResponseInfoInternal(resInfo);
171 cadata->responseInfo = resInfo;
172 info = &resInfo->info;
175 info->identity = *identity;
177 OIC_LOG(DEBUG, TAG, "Response Info :");
178 CALogPayloadInfo(info);
180 else if (CA_REQUEST_DATA == dataType)
182 CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
185 OIC_LOG(ERROR, TAG, "memory allocation failed");
189 CAResult_t result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
190 if (CA_STATUS_OK != result)
192 OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
193 CADestroyRequestInfoInternal(reqInfo);
197 if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
198 reqInfo->info.token, reqInfo->info.tokenLength))
200 OIC_LOG(INFO, TAG, "Second Request with same Token, Drop it");
201 CADestroyRequestInfoInternal(reqInfo);
205 cadata->requestInfo = reqInfo;
206 info = &reqInfo->info;
209 info->identity = *identity;
211 OIC_LOG(DEBUG, TAG, "Request Info :");
212 CALogPayloadInfo(info);
214 else if (CA_ERROR_DATA == dataType)
216 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
219 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
223 CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
224 if (CA_STATUS_OK != result)
226 OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
231 cadata->errorInfo = errorInfo;
232 info = &errorInfo->info;
235 info->identity = *identity;
237 OIC_LOG(DEBUG, TAG, "error Info :");
238 CALogPayloadInfo(info);
241 cadata->remoteEndpoint = ep;
242 cadata->dataType = dataType;
244 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
249 #ifndef SINGLE_THREAD
255 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
257 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
258 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
260 CAEndpoint_t* ep = endpoint;
262 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
265 OIC_LOG(ERROR, TAG, "clone failed");
270 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
274 OIC_LOG(ERROR, TAG, "calloc failed");
275 #ifndef SINGLE_THREAD
281 resInfo->result = CA_RETRANSMIT_TIMEOUT;
282 resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
283 resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
285 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *) pdu, &(resInfo->info),
287 if (CA_STATUS_OK != res)
289 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
290 CADestroyResponseInfoInternal(resInfo);
291 #ifndef SINGLE_THREAD
297 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
300 OIC_LOG(ERROR, TAG, "memory allocation failed !");
301 #ifndef SINGLE_THREAD
304 CADestroyResponseInfoInternal(resInfo);
308 cadata->type = SEND_TYPE_UNICAST;
309 cadata->remoteEndpoint = ep;
310 cadata->requestInfo = NULL;
311 cadata->responseInfo = resInfo;
314 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
316 res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
317 endpoint->addr, endpoint->port);
318 if (CA_STATUS_OK != res)
320 OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
326 CAProcessReceivedData(cadata);
328 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
332 static void CADestroyData(void *data, uint32_t size)
334 OIC_LOG(DEBUG, TAG, "CADestroyData IN");
335 if ((size_t)size < sizeof(CAData_t))
337 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
339 CAData_t *cadata = (CAData_t *) data;
343 OIC_LOG(ERROR, TAG, "cadata is NULL");
346 #ifndef SINGLE_THREAD
347 if (NULL != cadata->remoteEndpoint)
349 CAFreeEndpoint(cadata->remoteEndpoint);
353 if (NULL != cadata->requestInfo)
355 CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
358 if (NULL != cadata->responseInfo)
360 CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
363 if (NULL != cadata->errorInfo)
365 CADestroyErrorInfoInternal(cadata->errorInfo);
369 OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
373 static void CAProcessReceivedData(CAData_t *data)
375 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
378 OIC_LOG(ERROR, TAG, "thread data error!!");
382 // parse the data and call the callbacks.
385 CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
388 OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
392 if (data->requestInfo && g_requestHandler)
394 g_requestHandler(rep, data->requestInfo);
396 else if (data->responseInfo && g_responseHandler)
398 g_responseHandler(rep, data->responseInfo);
400 else if (data->errorInfo && g_errorHandler)
402 g_errorHandler(rep, data->errorInfo);
405 CADestroyData(data, sizeof(CAData_t));
407 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
411 #ifndef SINGLE_THREAD
412 static void CAReceiveThreadProcess(void *threadData)
414 #ifndef SINGLE_HANDLE
415 CAData_t *data = (CAData_t *) threadData;
416 CAProcessReceivedData(data);
421 #endif // SINGLE_THREAD
423 static CAResult_t CAProcessMulticastData(const CAData_t *data)
425 VERIFY_NON_NULL(data, TAG, "data");
426 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
428 coap_pdu_t *pdu = NULL;
429 CAInfo_t *info = NULL;
430 coap_list_t *options = NULL;
431 coap_transport_t transport = COAP_UDP;
432 CAResult_t res = CA_SEND_FAILED;
434 if (!data->requestInfo && !data->responseInfo)
436 OIC_LOG(ERROR, TAG, "request or response info is empty");
440 if (data->requestInfo)
442 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
444 info = &data->requestInfo->info;
445 pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
447 else if (data->responseInfo)
449 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
451 info = &data->responseInfo->info;
452 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
453 &options, &transport);
458 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
459 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
460 coap_delete_list(options);
465 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
467 // Blockwise transfer
468 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
469 if (CA_STATUS_OK != res)
471 OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
477 CALogPDUInfo(data, pdu);
479 res = CASendMulticastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
480 if (CA_STATUS_OK != res)
482 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
486 coap_delete_list(options);
487 coap_delete_pdu(pdu);
491 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
492 coap_delete_list(options);
493 coap_delete_pdu(pdu);
497 static CAResult_t CAProcessSendData(const CAData_t *data)
499 VERIFY_NON_NULL(data, TAG, "data");
500 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
502 CAResult_t res = CA_STATUS_FAILED;
504 CASendDataType_t type = data->type;
506 coap_pdu_t *pdu = NULL;
507 CAInfo_t *info = NULL;
508 coap_list_t *options = NULL;
509 coap_transport_t transport = COAP_UDP;
511 if (SEND_TYPE_UNICAST == type)
513 OIC_LOG(DEBUG,TAG,"Unicast message");
515 #ifdef ROUTING_GATEWAY
517 * When forwarding a packet, do not attempt retransmission as its the responsibility of
518 * packet originator node
520 bool skipRetransmission = false;
523 if (NULL != data->requestInfo)
525 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
527 info = &data->requestInfo->info;
528 #ifdef ROUTING_GATEWAY
529 skipRetransmission = data->requestInfo->info.skipRetransmission;
531 pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
532 &options, &transport);
534 else if (NULL != data->responseInfo)
536 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
538 info = &data->responseInfo->info;
539 #ifdef ROUTING_GATEWAY
540 skipRetransmission = data->responseInfo->info.skipRetransmission;
542 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
543 &options, &transport);
547 OIC_LOG(DEBUG, TAG, "request info, response info is empty");
548 return CA_STATUS_INVALID_PARAM;
551 // interface controller function call.
555 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
557 // Blockwise transfer
560 CAResult_t res = CAAddBlockOption(&pdu, info,
561 data->remoteEndpoint,
563 if (CA_STATUS_OK != res)
565 OIC_LOG(INFO, TAG, "to write block option has failed");
566 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
567 coap_delete_list(options);
568 coap_delete_pdu(pdu);
574 CALogPDUInfo(data, pdu);
576 OIC_LOG_V(INFO, TAG, "CASendUnicastData type : %d", data->dataType);
577 res = CASendUnicastData(data->remoteEndpoint, pdu->transport_hdr, pdu->length, data->dataType);
578 if (CA_STATUS_OK != res)
580 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
581 CAErrorHandler(data->remoteEndpoint, pdu->transport_hdr, pdu->length, res);
582 coap_delete_list(options);
583 coap_delete_pdu(pdu);
588 if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
590 OIC_LOG(INFO, TAG, "retransmission will be not worked");
594 #ifdef ROUTING_GATEWAY
595 if (!skipRetransmission)
598 // for retransmission
599 res = CARetransmissionSentData(&g_retransmissionContext,
600 data->remoteEndpoint,
602 pdu->transport_hdr, pdu->length);
603 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
605 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
606 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
607 coap_delete_list(options);
608 coap_delete_pdu(pdu);
613 coap_delete_list(options);
614 coap_delete_pdu(pdu);
618 OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
619 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
620 return CA_SEND_FAILED;
623 else if (SEND_TYPE_MULTICAST == type)
625 OIC_LOG(DEBUG,TAG,"Multicast message");
628 * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
629 * That's why we need to generate two pdu's, one for IP and second for other transports.
630 * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
631 * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
633 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
634 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
635 CA_ADAPTER_IP != data->remoteEndpoint->adapter))
637 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
639 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
643 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
645 CAProcessMulticastData(data);
646 data->remoteEndpoint->adapter = CA_ADAPTER_IP;
647 CAProcessMulticastData(data);
651 CAProcessMulticastData(data);
654 CAProcessMulticastData(data);
661 #ifndef SINGLE_THREAD
662 static void CASendThreadProcess(void *threadData)
664 CAData_t *data = (CAData_t *) threadData;
665 CAProcessSendData(data);
670 * If a second message arrives with the same message ID, token and the other address
671 * family, drop it. Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
673 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
674 CAToken_t token, uint8_t tokenLength)
680 if (ep->adapter != CA_ADAPTER_IP)
684 if (!caglobals.ip.dualstack)
689 if (tokenLength > CA_MAX_TOKEN_LEN)
692 * If token length is more than CA_MAX_TOKEN_LEN,
693 * we compare the first CA_MAX_TOKEN_LEN bytes only.
695 tokenLength = CA_MAX_TOKEN_LEN;
699 CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
701 for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
703 CAHistoryItem_t *item = &(history->items[i]);
704 if (id == item->messageId && tokenLength == item->tokenLength
705 && ep->ifindex == item->ifindex && memcmp(item->token, token, tokenLength) == 0)
707 if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
709 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
710 familyFlags & CA_IPV6 ? '6' : '4');
717 history->items[history->nextIndex].flags = familyFlags;
718 history->items[history->nextIndex].messageId = id;
719 history->items[history->nextIndex].ifindex = ep->ifindex;
720 if (token && tokenLength)
722 memcpy(history->items[history->nextIndex].token, token, tokenLength);
723 history->items[history->nextIndex].tokenLength = tokenLength;
726 if (++history->nextIndex >= HISTORYSIZE)
728 history->nextIndex = 0;
734 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
735 const void *data, size_t dataLen)
737 VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
738 VERIFY_NON_NULL_VOID(data, TAG, "data");
742 OIC_LOG(ERROR, TAG, "dataLen is zero");
746 uint32_t code = CA_NOT_FOUND;
747 CAData_t *cadata = NULL;
749 coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
753 OIC_LOG(ERROR, TAG, "Parse PDU failed");
757 OIC_LOG_V(DEBUG, TAG, "code = %d", code);
758 if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
760 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
763 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
764 coap_delete_pdu(pdu);
770 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
773 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
774 coap_delete_pdu(pdu);
779 if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
781 OIC_LOG(INFO, TAG, "retransmission is not supported");
786 // for retransmission
787 void *retransmissionPdu = NULL;
788 CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->transport_hdr,
789 pdu->length, &retransmissionPdu);
791 // get token from saved data in retransmission list
792 if (retransmissionPdu && CA_EMPTY == code)
794 if (cadata->responseInfo)
796 CAInfo_t *info = &cadata->responseInfo->info;
797 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_transport_t *)retransmissionPdu,
798 info, &(sep->endpoint));
799 if (CA_STATUS_OK != res)
801 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
802 OICFree(info->token);
803 info->tokenLength = 0;
807 OICFree(retransmissionPdu);
811 cadata->type = SEND_TYPE_UNICAST;
813 CALogPDUInfo(cadata, pdu);
816 CAProcessReceivedData(cadata);
819 if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
821 CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
822 if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
824 OIC_LOG(DEBUG, TAG, "this message does not have block option");
825 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
829 CADestroyData(cadata, sizeof(CAData_t));
835 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
837 #endif // SINGLE_THREAD
839 coap_delete_pdu(pdu);
842 OIC_LOG(DEBUG, TAG, "received pdu data :");
843 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLen);
846 void CAHandleRequestResponseCallbacks()
850 CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
853 // parse the data and call the callbacks.
857 oc_mutex_lock(g_receiveThread.threadMutex);
859 u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
861 oc_mutex_unlock(g_receiveThread.threadMutex);
863 if (NULL == item || NULL == item->msg)
869 CAData_t *td = (CAData_t *) item->msg;
871 if (td->requestInfo && g_requestHandler)
873 OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
874 g_requestHandler(td->remoteEndpoint, td->requestInfo);
876 else if (td->responseInfo && g_responseHandler)
878 OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
879 g_responseHandler(td->remoteEndpoint, td->responseInfo);
881 else if (td->errorInfo && g_errorHandler)
883 OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
884 g_errorHandler(td->remoteEndpoint, td->errorInfo);
887 CADestroyData(item->msg, sizeof(CAData_t));
890 #endif // SINGLE_HANDLE
891 #endif // SINGLE_THREAD
894 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
895 CADataType_t dataType)
897 OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
899 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
902 OIC_LOG(ERROR, TAG, "memory allocation failed");
906 if (CA_REQUEST_DATA == dataType)
909 CARequestInfo_t *request = (CARequestInfo_t *)sendData;
911 // clone request info
912 CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
915 OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
919 cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
920 cadata->requestInfo = request;
922 else if (CA_RESPONSE_DATA == dataType || CA_RESPONSE_FOR_RES == dataType)
925 CAResponseInfo_t *response = (CAResponseInfo_t *)sendData;
927 // clone response info
928 CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
931 OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
935 cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
936 cadata->responseInfo = response;
940 OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
945 CAEndpoint_t* ep = endpoint;
947 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
950 OIC_LOG(ERROR, TAG, "endpoint clone failed");
954 cadata->remoteEndpoint = ep;
955 cadata->dataType = dataType;
959 #ifndef SINGLE_THREAD
960 CADestroyData(cadata, sizeof(CAData_t));
967 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
968 CADataType_t dataType)
970 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
971 VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
973 if (false == CAIsSelectedNetworkAvailable())
975 return CA_STATUS_FAILED;
979 // If max retransmission queue is reached, then don't handle new request
980 if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
982 OIC_LOG(ERROR, TAG, "max RT queue size reached!");
983 return CA_SEND_FAILED;
987 CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
990 OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
991 return CA_MEMORY_ALLOC_FAILED;
994 OIC_LOG_V(DEBUG, TAG, "device ID of endpoint of this message is %s", endpoint->deviceId);
997 CAResult_t result = CAProcessSendData(data);
998 if (CA_STATUS_OK != result)
1000 OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
1008 if (SEND_TYPE_UNICAST == data->type && CAIsLocalEndpoint(data->remoteEndpoint))
1011 "This is a loopback message. Transfer it to the receive queue directly");
1012 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
1013 return CA_STATUS_OK;
1016 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
1019 CAResult_t res = CASendBlockWiseData(data);
1020 if (CA_NOT_SUPPORTED == res)
1022 OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1023 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1024 return CA_STATUS_OK;
1028 CADestroyData(data, sizeof(CAData_t));
1035 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1037 #endif // SINGLE_THREAD
1039 return CA_STATUS_OK;
1042 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1043 CAErrorCallback errorHandler)
1045 g_requestHandler = ReqHandler;
1046 g_responseHandler = RespHandler;
1047 g_errorHandler = errorHandler;
1050 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1052 g_nwMonitorHandler = nwMonitorHandler;
1055 CAResult_t CAInitializeMessageHandler()
1057 CASetPacketReceivedCallback(CAReceivedPacketCallback);
1058 CASetErrorHandleCallback(CAErrorHandler);
1060 #ifndef SINGLE_THREAD
1061 // create thread pool
1062 CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1063 if (CA_STATUS_OK != res)
1065 OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1069 // send thread initialize
1070 res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1071 CASendThreadProcess, CADestroyData);
1072 if (CA_STATUS_OK != res)
1074 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1078 // start send thread
1079 res = CAQueueingThreadStart(&g_sendThread);
1080 if (CA_STATUS_OK != res)
1082 OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1086 // receive thread initialize
1087 res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1088 CAReceiveThreadProcess, CADestroyData);
1089 if (CA_STATUS_OK != res)
1091 OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1095 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1096 // start receive thread
1097 res = CAQueueingThreadStart(&g_receiveThread);
1098 if (CA_STATUS_OK != res)
1100 OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1103 #endif // SINGLE_HANDLE
1105 // retransmission initialize
1106 res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1107 CASendUnicastData, CATimeoutCallback, NULL);
1108 if (CA_STATUS_OK != res)
1110 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1115 // block-wise transfer initialize
1116 res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1117 if (CA_STATUS_OK != res)
1119 OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1124 // start retransmission
1125 res = CARetransmissionStart(&g_retransmissionContext);
1126 if (CA_STATUS_OK != res)
1128 OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1132 // initialize interface adapters by controller
1133 CAInitializeAdapters(g_threadPoolHandle);
1135 // retransmission initialize
1136 CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1137 CATimeoutCallback, NULL);
1138 if (CA_STATUS_OK != res)
1140 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1144 CAInitializeAdapters();
1145 #endif // SINGLE_THREAD
1147 return CA_STATUS_OK;
1150 void CATerminateMessageHandler()
1152 #ifndef SINGLE_THREAD
1153 CATransportAdapter_t connType;
1154 u_arraylist_t *list = CAGetSelectedNetworkList();
1155 uint32_t length = u_arraylist_length(list);
1158 for (i = 0; i < length; i++)
1160 void* ptrType = u_arraylist_get(list, i);
1162 if (NULL == ptrType)
1167 connType = *(CATransportAdapter_t *)ptrType;
1168 CAStopAdapter(connType);
1171 // stop retransmission
1172 if (NULL != g_retransmissionContext.threadMutex)
1174 CARetransmissionStop(&g_retransmissionContext);
1178 // delete thread data
1179 if (NULL != g_sendThread.threadMutex)
1181 CAQueueingThreadStop(&g_sendThread);
1185 // delete thread data
1186 if (NULL != g_receiveThread.threadMutex)
1188 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1189 CAQueueingThreadStop(&g_receiveThread);
1193 // destroy thread pool
1194 if (NULL != g_threadPoolHandle)
1196 ca_thread_pool_free(g_threadPoolHandle);
1197 g_threadPoolHandle = NULL;
1201 CATerminateBlockWiseTransfer();
1203 CARetransmissionDestroy(&g_retransmissionContext);
1204 CAQueueingThreadDestroy(&g_sendThread);
1205 CAQueueingThreadDestroy(&g_receiveThread);
1207 // terminate interface adapters by controller
1208 CATerminateAdapters();
1210 // terminate interface adapters by controller
1211 CATerminateAdapters();
1213 // stop retransmission
1214 CARetransmissionStop(&g_retransmissionContext);
1215 CARetransmissionDestroy(&g_retransmissionContext);
1216 #endif // SINGLE_THREAD
1219 static void CALogPayloadInfo(CAInfo_t *info)
1225 for (uint32_t i = 0; i < info->numOptions; i++)
1227 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1229 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1235 OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1241 OIC_LOG(DEBUG, TAG, "token:");
1242 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1245 OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1249 OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1253 void CAErrorHandler(const CAEndpoint_t *endpoint,
1254 const void *data, size_t dataLen,
1257 OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1258 VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1259 VERIFY_NON_NULL_VOID(data, TAG, "data");
1263 OIC_LOG(ERROR, TAG, "dataLen is zero");
1267 #ifndef SINGLE_THREAD
1268 uint32_t code = CA_NOT_FOUND;
1269 //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1271 coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1274 OIC_LOG(ERROR, TAG, "Parse PDU failed");
1278 CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1281 OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1282 coap_delete_pdu(pdu);
1286 cadata->errorInfo->result = result;
1288 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1289 coap_delete_pdu(pdu);
1294 OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1298 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1300 OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1301 #ifndef SINGLE_THREAD
1302 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1305 OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1309 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1312 OIC_LOG(ERROR, TAG, "endpoint clone failed");
1317 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1320 OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1326 CAResult_t res = CACloneInfo(info, &errorInfo->info);
1327 if (CA_STATUS_OK != res)
1329 OIC_LOG(ERROR, TAG, "info clone failed");
1336 errorInfo->result = result;
1337 cadata->remoteEndpoint = ep;
1338 cadata->errorInfo = errorInfo;
1339 cadata->dataType = CA_ERROR_DATA;
1341 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1343 OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");
1347 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1349 OIC_LOG(DEBUG, TAG, "CALogPDUInfo");
1351 VERIFY_NON_NULL_VOID(data, TAG, "data");
1352 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1354 OIC_LOG(DEBUG, ANALYZER_TAG, "=================================================");
1355 if(SEND_TYPE_MULTICAST == data->type)
1357 OIC_LOG(DEBUG, ANALYZER_TAG, "Is Multicast = true");
1361 OIC_LOG(DEBUG, ANALYZER_TAG, "Is Multicast = false");
1364 if (NULL != data->remoteEndpoint)
1366 CALogAdapterTypeInfo(data->remoteEndpoint->adapter);
1367 OIC_LOG(DEBUG, ANALYZER_TAG, "-------------------------------------------------");
1368 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Address = [%s]:[%d]", data->remoteEndpoint->addr,
1369 data->remoteEndpoint->port);
1370 OIC_LOG(DEBUG, ANALYZER_TAG, "-------------------------------------------------");
1373 switch(data->dataType)
1375 case CA_REQUEST_DATA:
1376 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_REQUEST_DATA]");
1378 case CA_RESPONSE_DATA:
1379 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_RESPONSE_DATA]");
1382 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_ERROR_DATA]");
1384 case CA_RESPONSE_FOR_RES:
1385 OIC_LOG(DEBUG, ANALYZER_TAG, "Data Type = [CA_RESPONSE_FOR_RES]");
1388 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Data Type = [%d]", data->dataType);
1391 OIC_LOG(DEBUG, ANALYZER_TAG, "-------------------------------------------------");
1393 const CAInfo_t *info = NULL;
1394 if (NULL != data->requestInfo)
1396 switch(data->requestInfo->method)
1399 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [GET]");
1402 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [POST]");
1405 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [PUT]");
1408 OIC_LOG(DEBUG, ANALYZER_TAG, "Method = [DELETE]");
1411 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Method = [%d]", data->requestInfo->method);
1414 info = &data->requestInfo->info;
1417 if (NULL != data->responseInfo)
1419 OIC_LOG_V(DEBUG, ANALYZER_TAG, "result code = [%d]", data->responseInfo->result);
1420 info = &data->responseInfo->info;
1423 if (pdu->transport_hdr)
1425 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Msg ID = [%d]", pdu->transport_hdr->udp.id);
1430 OIC_LOG(DEBUG, ANALYZER_TAG, "Coap Token");
1431 OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, (const uint8_t *) info->token, info->tokenLength);
1432 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Res URI = [%s]", info->resourceUri);
1433 OIC_LOG(DEBUG, ANALYZER_TAG, "-------------------------------------------------");
1435 if (CA_FORMAT_APPLICATION_CBOR == info->payloadFormat)
1437 OIC_LOG(DEBUG, ANALYZER_TAG, "Payload Format = [CA_FORMAT_APPLICATION_CBOR]");
1441 OIC_LOG_V(DEBUG, ANALYZER_TAG, "Payload Format = [%d]", info->payloadFormat);
1445 size_t payloadLen = (pdu->data) ? (unsigned char *) pdu->hdr + pdu->length - pdu->data : 0;
1446 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Message Full Size = [%lu]", pdu->length);
1447 OIC_LOG(DEBUG, ANALYZER_TAG, "CoAP Header (+ 0xFF)");
1448 OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, (const uint8_t *) pdu->transport_hdr,
1449 pdu->length - payloadLen);
1450 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Header size = [%lu]", pdu->length - payloadLen);
1452 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload");
1453 OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, pdu->data, payloadLen);
1454 OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload Size = [%lu]", payloadLen);
1455 OIC_LOG(DEBUG, ANALYZER_TAG, "=================================================");
1458 static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
1460 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1463 OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1464 OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->transport_hdr->udp.type);
1465 OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->transport_hdr->udp.code);
1466 OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1467 OIC_LOG_BUFFER(DEBUG, TAG, pdu->transport_hdr->udp.token,
1468 pdu->transport_hdr->udp.token_length);