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"
39 #include "cablockwisetransfer.h"
44 #include "cathreadpool.h" /* for thread pool */
45 #include "caqueueingthread.h"
48 #define MAX_THREAD_POOL_SIZE 20
51 static ca_thread_pool_t g_threadPoolHandle = NULL;
53 // message handler main thread
54 static CAQueueingThread_t g_sendThread;
55 static CAQueueingThread_t g_receiveThread;
58 #define CA_MAX_RT_ARRAY_SIZE 3
59 #endif // SINGLE_THREAD
61 #define TAG "OIC_CA_MSG_HANDLE"
63 static CARetransmission_t g_retransmissionContext;
66 static CARequestCallback g_requestHandler = NULL;
67 static CAResponseCallback g_responseHandler = NULL;
68 static CAErrorCallback g_errorHandler = NULL;
69 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
71 static void CAErrorHandler(const CAEndpoint_t *endpoint,
72 const void *data, uint32_t dataLen,
75 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
76 const CARemoteId_t *identity,
77 const void *data, CADataType_t dataType);
79 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
83 static void CAProcessReceivedData(CAData_t *data);
85 static void CADestroyData(void *data, uint32_t size);
86 static void CALogPayloadInfo(CAInfo_t *info);
87 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
88 CAToken_t token, uint8_t tokenLength);
91 void CAAddDataToSendThread(CAData_t *data)
93 VERIFY_NON_NULL_VOID(data, TAG, "data");
96 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
99 void CAAddDataToReceiveThread(CAData_t *data)
101 VERIFY_NON_NULL_VOID(data, TAG, "data");
104 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
108 static bool CAIsSelectedNetworkAvailable()
110 u_arraylist_t *list = CAGetSelectedNetworkList();
111 if (!list || u_arraylist_length(list) == 0)
113 OIC_LOG(ERROR, TAG, "No selected network");
120 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
121 const CARemoteId_t *identity,
122 const void *data, CADataType_t dataType)
124 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
125 CAInfo_t *info = NULL;
126 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
129 OIC_LOG(ERROR, TAG, "memory allocation failed");
133 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
136 OIC_LOG(ERROR, TAG, "endpoint clone failed");
141 OIC_LOG_V(DEBUG, TAG, "address : %s", ep->addr);
144 if(CA_RESPONSE_DATA == dataType)
146 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
149 OIC_LOG(ERROR, TAG, "memory allocation failed");
155 result = CAGetResponseInfoFromPDU(data, resInfo, endpoint);
156 if (CA_STATUS_OK != result)
158 OIC_LOG(ERROR, TAG, "CAGetResponseInfoFromPDU Failed");
160 CADestroyResponseInfoInternal(resInfo);
164 cadata->responseInfo = resInfo;
165 info = &resInfo->info;
168 info->identity = *identity;
170 OIC_LOG(DEBUG, TAG, "Response Info :");
171 CALogPayloadInfo(info);
173 else if (CA_REQUEST_DATA == dataType)
175 CARequestInfo_t* reqInfo = (CARequestInfo_t*)OICCalloc(1, sizeof(CARequestInfo_t));
178 OIC_LOG(ERROR, TAG, "memory allocation failed");
184 result = CAGetRequestInfoFromPDU(data, endpoint, reqInfo);
185 if (CA_STATUS_OK != result)
187 OIC_LOG(ERROR, TAG, "CAGetRequestInfoFromPDU failed");
189 CADestroyRequestInfoInternal(reqInfo);
194 if (CADropSecondMessage(&caglobals.ca.requestHistory, endpoint, reqInfo->info.messageId,
195 reqInfo->info.token, reqInfo->info.tokenLength))
197 OIC_LOG(ERROR, TAG, "Second Request with same Token, Drop it");
199 CADestroyRequestInfoInternal(reqInfo);
204 cadata->requestInfo = reqInfo;
205 info = &reqInfo->info;
208 info->identity = *identity;
210 OIC_LOG(DEBUG, TAG, "Request Info :");
211 CALogPayloadInfo(info);
213 else if (CA_ERROR_DATA == dataType)
215 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
218 OIC_LOG(ERROR, TAG, "Memory allocation failed!");
224 CAResult_t result = CAGetErrorInfoFromPDU(data, endpoint, errorInfo);
225 if (CA_STATUS_OK != result)
227 OIC_LOG(ERROR, TAG, "CAGetErrorInfoFromPDU failed");
234 cadata->errorInfo = errorInfo;
235 info = &errorInfo->info;
238 info->identity = *identity;
240 OIC_LOG(DEBUG, TAG, "error Info :");
241 CALogPayloadInfo(info);
244 cadata->remoteEndpoint = ep;
245 cadata->dataType = dataType;
247 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData OUT");
251 static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
253 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
254 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
256 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
259 OIC_LOG(ERROR, TAG, "clone failed");
263 CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(CAResponseInfo_t));
267 OIC_LOG(ERROR, TAG, "calloc failed");
272 resInfo->result = CA_RETRANSMIT_TIMEOUT;
273 resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);
274 resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
276 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *) pdu, &(resInfo->info),
278 if (CA_STATUS_OK != res)
280 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
281 CADestroyResponseInfoInternal(resInfo);
286 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
289 OIC_LOG(ERROR, TAG, "memory allocation failed !");
291 CADestroyResponseInfoInternal(resInfo);
295 cadata->type = SEND_TYPE_UNICAST;
296 cadata->remoteEndpoint = ep;
297 cadata->requestInfo = NULL;
298 cadata->responseInfo = resInfo;
301 CAProcessReceivedData(cadata);
303 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
307 static void CADestroyData(void *data, uint32_t size)
309 OIC_LOG(DEBUG, TAG, "CADestroyData IN");
310 if ((size_t)size < sizeof(CAData_t))
312 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
314 CAData_t *cadata = (CAData_t *) data;
318 OIC_LOG(ERROR, TAG, "cadata is NULL");
322 if (NULL != cadata->remoteEndpoint)
324 CAFreeEndpoint(cadata->remoteEndpoint);
327 if (NULL != cadata->requestInfo)
329 CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
332 if (NULL != cadata->responseInfo)
334 CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
337 if (NULL != cadata->errorInfo)
339 CADestroyErrorInfoInternal(cadata->errorInfo);
343 OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
347 static void CAProcessReceivedData(CAData_t *data)
349 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
352 OIC_LOG(ERROR, TAG, "thread data error!!");
356 // parse the data and call the callbacks.
359 CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
362 OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
366 if (data->requestInfo && g_requestHandler)
368 g_requestHandler(rep, data->requestInfo);
370 else if (data->responseInfo && g_responseHandler)
372 g_responseHandler(rep, data->responseInfo);
374 else if (data->errorInfo && g_errorHandler)
376 g_errorHandler(rep, data->errorInfo);
379 CADestroyData(data, sizeof(CAData_t));
381 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
385 #ifndef SINGLE_THREAD
386 static void CAReceiveThreadProcess(void *threadData)
388 #ifndef SINGLE_HANDLE
389 CAData_t *data = (CAData_t *) threadData;
390 CAProcessReceivedData(data);
395 #endif // SINGLE_THREAD
397 static CAResult_t CAProcessMulticastData(const CAData_t *data)
399 VERIFY_NON_NULL(data, TAG, "data");
400 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
402 coap_pdu_t *pdu = NULL;
403 CAInfo_t *info = NULL;
404 coap_list_t *options = NULL;
405 coap_transport_type transport;
406 CAResult_t res = CA_SEND_FAILED;
407 if (NULL != data->requestInfo)
409 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
411 info = &data->requestInfo->info;
412 pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
417 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
419 // Blockwise transfer
420 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
421 if (CA_STATUS_OK != res)
423 OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
431 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
432 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
436 else if (NULL != data->responseInfo)
438 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
440 info = &data->responseInfo->info;
441 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
442 &options, &transport);
447 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
449 // Blockwise transfer
452 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
453 if (CA_STATUS_OK != res)
455 OIC_LOG(INFO, TAG, "to write block option has failed");
464 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
465 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
471 OIC_LOG(ERROR, TAG, "request or response info is empty");
475 CALogPDUInfo(pdu, data->remoteEndpoint);
477 OIC_LOG(DEBUG, TAG, "pdu to send :");
478 OIC_LOG_BUFFER(DEBUG, TAG, (uint8_t*)pdu->hdr, pdu->length);
480 res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
481 if (CA_STATUS_OK != res)
483 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
487 coap_delete_list(options);
488 coap_delete_pdu(pdu);
492 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
493 coap_delete_list(options);
494 coap_delete_pdu(pdu);
498 static CAResult_t CAProcessSendData(const CAData_t *data)
500 VERIFY_NON_NULL(data, TAG, "data");
501 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
503 CAResult_t res = CA_STATUS_FAILED;
505 CASendDataType_t type = data->type;
507 coap_pdu_t *pdu = NULL;
508 CAInfo_t *info = NULL;
509 coap_list_t *options = NULL;
510 coap_transport_type transport;
512 if (SEND_TYPE_UNICAST == type)
514 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->hdr, pdu->length, res);
567 coap_delete_list(options);
568 coap_delete_pdu(pdu);
574 CALogPDUInfo(pdu, data->remoteEndpoint);
576 res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
577 if (CA_STATUS_OK != res)
579 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
580 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
581 coap_delete_list(options);
582 coap_delete_pdu(pdu);
587 if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
589 OIC_LOG(INFO, TAG, "retransmission will be not worked");
593 #ifdef ROUTING_GATEWAY
594 if(!skipRetransmission)
597 // for retransmission
598 res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint,
599 pdu->hdr, pdu->length);
600 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
602 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
603 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
604 coap_delete_list(options);
605 coap_delete_pdu(pdu);
610 coap_delete_list(options);
611 coap_delete_pdu(pdu);
615 OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
616 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
617 return CA_SEND_FAILED;
620 else if (SEND_TYPE_MULTICAST == type)
622 OIC_LOG(DEBUG,TAG,"Multicast message");
625 * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
626 * That's why we need to generate two pdu's, one for IP and second for other transports.
627 * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
628 * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
630 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
631 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
632 CA_ADAPTER_IP != data->remoteEndpoint->adapter))
634 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
636 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
640 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
642 CAProcessMulticastData(data);
643 data->remoteEndpoint->adapter = CA_ADAPTER_IP;
644 CAProcessMulticastData(data);
648 CAProcessMulticastData(data);
651 CAProcessMulticastData(data);
658 #ifndef SINGLE_THREAD
659 static void CASendThreadProcess(void *threadData)
661 CAData_t *data = (CAData_t *) threadData;
662 CAProcessSendData(data);
667 * If a second message arrives with the same message ID, token and the other address
668 * family, drop it. Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
670 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
671 CAToken_t token, uint8_t tokenLength)
677 if (ep->adapter != CA_ADAPTER_IP)
681 if (!caglobals.ip.dualstack)
686 if (tokenLength > CA_MAX_TOKEN_LEN)
689 * If token length is more than CA_MAX_TOKEN_LEN,
690 * we compare the first CA_MAX_TOKEN_LEN bytes only.
692 tokenLength = CA_MAX_TOKEN_LEN;
696 CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
698 for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
700 CAHistoryItem_t *item = &(history->items[i]);
701 if (id == item->messageId && tokenLength == item->tokenLength
702 && memcmp(item->token, token, tokenLength) == 0)
704 if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
706 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
707 familyFlags & CA_IPV6 ? '6' : '4');
714 history->items[history->nextIndex].flags = familyFlags;
715 history->items[history->nextIndex].messageId = id;
716 if (token && tokenLength)
718 memcpy(history->items[history->nextIndex].token, token, tokenLength);
719 history->items[history->nextIndex].tokenLength = tokenLength;
722 if (++history->nextIndex >= HISTORYSIZE)
724 history->nextIndex = 0;
730 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
731 const void *data, uint32_t dataLen)
733 VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
734 VERIFY_NON_NULL_VOID(data, TAG, "data");
736 OIC_LOG(DEBUG, TAG, "received pdu data :");
737 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLen);
739 uint32_t code = CA_NOT_FOUND;
740 CAData_t *cadata = NULL;
742 coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
746 OIC_LOG(ERROR, TAG, "Parse PDU failed");
750 OIC_LOG_V(DEBUG, TAG, "code = %d", code);
751 if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
753 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
756 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
757 coap_delete_pdu(pdu);
763 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
766 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
767 coap_delete_pdu(pdu);
772 if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
774 OIC_LOG(INFO, TAG, "retransmission is not supported");
779 // for retransmission
780 void *retransmissionPdu = NULL;
781 CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
782 pdu->length, &retransmissionPdu);
785 // get token from saved data in retransmission list
786 if (retransmissionPdu && CA_EMPTY == code)
788 if (cadata->responseInfo)
790 CAInfo_t *info = &cadata->responseInfo->info;
791 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
792 info, &(sep->endpoint));
793 if (CA_STATUS_OK != res)
795 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
796 OICFree(info->token);
797 info->tokenLength = 0;
802 OICFree(retransmissionPdu);
806 cadata->type = SEND_TYPE_UNICAST;
809 CAProcessReceivedData(cadata);
812 if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
814 CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
815 if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
817 OIC_LOG(ERROR, TAG, "this message does not have block option");
818 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
822 CADestroyData(cadata, sizeof(CAData_t));
828 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
830 #endif // SINGLE_THREAD
832 coap_delete_pdu(pdu);
835 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
840 if (g_nwMonitorHandler)
842 g_nwMonitorHandler(info, status);
846 void CAHandleRequestResponseCallbacks()
850 CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
853 // parse the data and call the callbacks.
857 ca_mutex_lock(g_receiveThread.threadMutex);
859 u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
861 ca_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)
908 // clone request info
909 CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
913 OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
917 cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
918 cadata->requestInfo = request;
920 else if(CA_RESPONSE_DATA == dataType)
922 // clone response info
923 CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
927 OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
931 cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
932 cadata->responseInfo = response;
936 OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
940 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
943 OIC_LOG(ERROR, TAG, "endpoint clone failed");
944 CADestroyData(cadata, sizeof(CAData_t));
948 cadata->remoteEndpoint = ep;
949 cadata->dataType = dataType;
957 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
958 CADataType_t dataType)
960 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
961 VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
963 if (false == CAIsSelectedNetworkAvailable())
965 return CA_STATUS_FAILED;
969 // If max retransmission queue is reached, then don't handle new request
970 if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
972 OIC_LOG(ERROR, TAG, "max RT queue size reached!");
973 return CA_SEND_FAILED;
977 CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
980 OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
981 return CA_MEMORY_ALLOC_FAILED;
985 CAResult_t result = CAProcessSendData(data);
986 if(CA_STATUS_OK != result)
988 OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
989 CADestroyData(data, sizeof(CAData_t));
993 CADestroyData(data, sizeof(CAData_t));
996 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
999 CAResult_t res = CASendBlockWiseData(data);
1000 if(CA_NOT_SUPPORTED == res)
1002 OIC_LOG(DEBUG, TAG, "normal msg will be sent");
1003 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1004 return CA_STATUS_OK;
1008 CADestroyData(data, sizeof(CAData_t));
1015 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
1017 #endif // SINGLE_THREAD
1019 return CA_STATUS_OK;
1022 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1023 CAErrorCallback errorHandler)
1025 g_requestHandler = ReqHandler;
1026 g_responseHandler = RespHandler;
1027 g_errorHandler = errorHandler;
1030 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1032 g_nwMonitorHandler = nwMonitorHandler;
1035 CAResult_t CAInitializeMessageHandler()
1037 CASetPacketReceivedCallback(CAReceivedPacketCallback);
1039 CASetNetworkChangeCallback(CANetworkChangedCallback);
1040 CASetErrorHandleCallback(CAErrorHandler);
1042 #ifndef SINGLE_THREAD
1043 // create thread pool
1044 CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1045 if (CA_STATUS_OK != res)
1047 OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1051 // send thread initialize
1052 res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1053 CASendThreadProcess, CADestroyData);
1054 if (CA_STATUS_OK != res)
1056 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1057 ca_thread_pool_free(g_threadPoolHandle);
1058 g_threadPoolHandle = NULL;
1062 // start send thread
1063 res = CAQueueingThreadStart(&g_sendThread);
1064 if (CA_STATUS_OK != res)
1066 OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1067 ca_thread_pool_free(g_threadPoolHandle);
1068 g_threadPoolHandle = NULL;
1069 CAQueueingThreadDestroy(&g_sendThread);
1073 // receive thread initialize
1074 res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1075 CAReceiveThreadProcess, CADestroyData);
1076 if (CA_STATUS_OK != res)
1078 OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1079 ca_thread_pool_free(g_threadPoolHandle);
1080 g_threadPoolHandle = NULL;
1081 CAQueueingThreadDestroy(&g_sendThread);
1085 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1086 // start receive thread
1087 res = CAQueueingThreadStart(&g_receiveThread);
1088 if (CA_STATUS_OK != res)
1090 OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1091 ca_thread_pool_free(g_threadPoolHandle);
1092 g_threadPoolHandle = NULL;
1093 CAQueueingThreadDestroy(&g_sendThread);
1094 CAQueueingThreadDestroy(&g_receiveThread);
1097 #endif // SINGLE_HANDLE
1099 // retransmission initialize
1100 res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1101 CASendUnicastData, CATimeoutCallback, NULL);
1102 if (CA_STATUS_OK != res)
1104 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1105 ca_thread_pool_free(g_threadPoolHandle);
1106 g_threadPoolHandle = NULL;
1107 CAQueueingThreadDestroy(&g_sendThread);
1108 CAQueueingThreadDestroy(&g_receiveThread);
1113 // block-wise transfer initialize
1114 res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1115 if (CA_STATUS_OK != res)
1117 OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1118 ca_thread_pool_free(g_threadPoolHandle);
1119 g_threadPoolHandle = NULL;
1120 CAQueueingThreadDestroy(&g_sendThread);
1121 CAQueueingThreadDestroy(&g_receiveThread);
1122 CARetransmissionDestroy(&g_retransmissionContext);
1127 // start retransmission
1128 res = CARetransmissionStart(&g_retransmissionContext);
1129 if (CA_STATUS_OK != res)
1131 OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1132 ca_thread_pool_free(g_threadPoolHandle);
1133 g_threadPoolHandle = NULL;
1134 CAQueueingThreadDestroy(&g_sendThread);
1135 CAQueueingThreadDestroy(&g_receiveThread);
1136 CARetransmissionDestroy(&g_retransmissionContext);
1140 // initialize interface adapters by controller
1141 CAInitializeAdapters(g_threadPoolHandle);
1143 // retransmission initialize
1144 CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1145 CATimeoutCallback, NULL);
1146 if (CA_STATUS_OK != res)
1148 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1152 CAInitializeAdapters();
1153 #endif // SINGLE_THREAD
1155 return CA_STATUS_OK;
1158 void CATerminateMessageHandler()
1160 #ifndef SINGLE_THREAD
1161 CATransportAdapter_t connType;
1162 u_arraylist_t *list = CAGetSelectedNetworkList();
1163 uint32_t length = u_arraylist_length(list);
1166 for (i = 0; i < length; i++)
1168 void* ptrType = u_arraylist_get(list, i);
1170 if (NULL == ptrType)
1175 connType = *(CATransportAdapter_t *)ptrType;
1176 CAStopAdapter(connType);
1179 // stop retransmission
1180 if (NULL != g_retransmissionContext.threadMutex)
1182 CARetransmissionStop(&g_retransmissionContext);
1186 // delete thread data
1187 if (NULL != g_sendThread.threadMutex)
1189 CAQueueingThreadStop(&g_sendThread);
1193 // delete thread data
1194 if (NULL != g_receiveThread.threadMutex)
1196 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1197 CAQueueingThreadStop(&g_receiveThread);
1201 // destroy thread pool
1202 if (NULL != g_threadPoolHandle)
1204 ca_thread_pool_free(g_threadPoolHandle);
1205 g_threadPoolHandle = NULL;
1209 CATerminateBlockWiseTransfer();
1211 CARetransmissionDestroy(&g_retransmissionContext);
1212 CAQueueingThreadDestroy(&g_sendThread);
1213 CAQueueingThreadDestroy(&g_receiveThread);
1215 // terminate interface adapters by controller
1216 CATerminateAdapters();
1218 // terminate interface adapters by controller
1219 CATerminateAdapters();
1221 // stop retransmission
1222 CARetransmissionStop(&g_retransmissionContext);
1223 CARetransmissionDestroy(&g_retransmissionContext);
1224 #endif // SINGLE_THREAD
1227 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1229 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1230 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1232 OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1235 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1237 OIC_LOG(DEBUG, TAG, "pdu header data :");
1238 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) pdu->hdr, pdu->length);
1243 OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1245 OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1247 OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1249 OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1250 pdu->hdr->coap_hdr_udp_t.token_length);
1254 static void CALogPayloadInfo(CAInfo_t *info)
1260 for (uint32_t i = 0; i < info->numOptions; i++)
1262 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1264 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1270 OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1276 OIC_LOG(DEBUG, TAG, "token:");
1277 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1280 OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1284 OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1288 void CAErrorHandler(const CAEndpoint_t *endpoint,
1289 const void *data, uint32_t dataLen,
1292 OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1294 #ifndef SINGLE_THREAD
1295 VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1296 VERIFY_NON_NULL_VOID(data, TAG, "data");
1298 uint32_t code = CA_NOT_FOUND;
1299 //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1301 coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1304 OIC_LOG(ERROR, TAG, "Parse PDU failed");
1308 CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1311 OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1312 coap_delete_pdu(pdu);
1316 cadata->errorInfo->result = result;
1318 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1319 coap_delete_pdu(pdu);
1322 OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1326 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1328 OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1329 #ifndef SINGLE_THREAD
1330 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1333 OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1337 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1340 OIC_LOG(ERROR, TAG, "endpoint clone failed");
1345 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1348 OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1354 CAResult_t res = CACloneInfo(info, &errorInfo->info);
1355 if (CA_STATUS_OK != res)
1357 OIC_LOG(ERROR, TAG, "info clone failed");
1364 errorInfo->result = result;
1365 cadata->remoteEndpoint = ep;
1366 cadata->errorInfo = errorInfo;
1367 cadata->dataType = CA_ERROR_DATA;
1369 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1371 OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");