1 /* *****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
26 #include "cainterface.h"
27 #include "camessagehandler.h"
28 #include "caremotehandler.h"
29 #include "caprotocolmessage.h"
31 #include "config.h" /* for coap protocol */
32 #include "oic_malloc.h"
33 #include "canetworkconfigurator.h"
34 #include "caadapterutils.h"
35 #include "cainterfacecontroller.h"
36 #include "caretransmission.h"
37 #include "oic_string.h"
40 #include "cablockwisetransfer.h"
45 #include "cathreadpool.h" /* for thread pool */
46 #include "caqueueingthread.h"
49 #define MAX_THREAD_POOL_SIZE 20
52 static ca_thread_pool_t g_threadPoolHandle = NULL;
54 // message handler main thread
55 static CAQueueingThread_t g_sendThread;
56 static CAQueueingThread_t g_receiveThread;
59 #define CA_MAX_RT_ARRAY_SIZE 3
60 #endif // SINGLE_THREAD
62 #define TAG "OIC_CA_MSG_HANDLE"
64 static CARetransmission_t g_retransmissionContext;
67 static CARequestCallback g_requestHandler = NULL;
68 static CAResponseCallback g_responseHandler = NULL;
69 static CAErrorCallback g_errorHandler = NULL;
70 static CANetworkMonitorCallback g_nwMonitorHandler = NULL;
72 static void CAErrorHandler(const CAEndpoint_t *endpoint,
73 const void *data, uint32_t dataLen,
76 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
77 const CARemoteId_t *identity,
78 const void *data, CADataType_t dataType);
80 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info,
84 static void CAProcessReceivedData(CAData_t *data);
86 static void CADestroyData(void *data, uint32_t size);
87 static void CALogPayloadInfo(CAInfo_t *info);
88 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *endpoint, uint16_t id,
89 CAToken_t token, uint8_t tokenLength);
92 void CAAddDataToSendThread(CAData_t *data)
94 VERIFY_NON_NULL_VOID(data, TAG, "data");
97 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
100 void CAAddDataToReceiveThread(CAData_t *data)
102 VERIFY_NON_NULL_VOID(data, TAG, "data");
105 CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
109 static bool CAIsSelectedNetworkAvailable()
111 u_arraylist_t *list = CAGetSelectedNetworkList();
112 if (!list || u_arraylist_length(list) == 0)
114 OIC_LOG(ERROR, TAG, "No selected network");
121 static CAData_t* CAGenerateHandlerData(const CAEndpoint_t *endpoint,
122 const CARemoteId_t *identity,
123 const void *data, CADataType_t dataType)
125 OIC_LOG(DEBUG, TAG, "CAGenerateHandlerData IN");
126 CAInfo_t *info = NULL;
127 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
130 OIC_LOG(ERROR, TAG, "memory allocation failed");
134 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
137 OIC_LOG(ERROR, TAG, "endpoint clone failed");
142 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 CAResult_t 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 CAResult_t 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 if (CAIsSupportedBlockwiseTransfer(endpoint->adapter))
303 res = CARemoveBlockDataFromListWithSeed(resInfo->info.token, resInfo->info.tokenLength,
305 if (CA_STATUS_OK != res)
307 OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromListWithSeed failed");
313 CAProcessReceivedData(cadata);
315 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
319 static void CADestroyData(void *data, uint32_t size)
321 OIC_LOG(DEBUG, TAG, "CADestroyData IN");
322 if ((size_t)size < sizeof(CAData_t))
324 OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
326 CAData_t *cadata = (CAData_t *) data;
330 OIC_LOG(ERROR, TAG, "cadata is NULL");
334 if (NULL != cadata->remoteEndpoint)
336 CAFreeEndpoint(cadata->remoteEndpoint);
339 if (NULL != cadata->requestInfo)
341 CADestroyRequestInfoInternal((CARequestInfo_t *) cadata->requestInfo);
344 if (NULL != cadata->responseInfo)
346 CADestroyResponseInfoInternal((CAResponseInfo_t *) cadata->responseInfo);
349 if (NULL != cadata->errorInfo)
351 CADestroyErrorInfoInternal(cadata->errorInfo);
355 OIC_LOG(DEBUG, TAG, "CADestroyData OUT");
359 static void CAProcessReceivedData(CAData_t *data)
361 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData IN");
364 OIC_LOG(ERROR, TAG, "thread data error!!");
368 // parse the data and call the callbacks.
371 CAEndpoint_t *rep = (CAEndpoint_t *)(data->remoteEndpoint);
374 OIC_LOG(ERROR, TAG, "remoteEndpoint error!!");
378 if (data->requestInfo && g_requestHandler)
380 g_requestHandler(rep, data->requestInfo);
382 else if (data->responseInfo && g_responseHandler)
384 g_responseHandler(rep, data->responseInfo);
386 else if (data->errorInfo && g_errorHandler)
388 g_errorHandler(rep, data->errorInfo);
391 CADestroyData(data, sizeof(CAData_t));
393 OIC_LOG(DEBUG, TAG, "CAProcessReceivedData OUT");
397 #ifndef SINGLE_THREAD
398 static void CAReceiveThreadProcess(void *threadData)
400 #ifndef SINGLE_HANDLE
401 CAData_t *data = (CAData_t *) threadData;
402 CAProcessReceivedData(data);
407 #endif // SINGLE_THREAD
409 static CAResult_t CAProcessMulticastData(const CAData_t *data)
411 VERIFY_NON_NULL(data, TAG, "data");
412 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
414 coap_pdu_t *pdu = NULL;
415 CAInfo_t *info = NULL;
416 coap_list_t *options = NULL;
417 coap_transport_type transport = coap_udp;
418 CAResult_t res = CA_SEND_FAILED;
419 if (NULL != data->requestInfo)
421 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
423 info = &data->requestInfo->info;
424 pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
429 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
431 // Blockwise transfer
432 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
433 if (CA_STATUS_OK != res)
435 OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
443 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
444 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
448 else if (NULL != data->responseInfo)
450 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
452 info = &data->responseInfo->info;
453 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
454 &options, &transport);
459 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
461 // Blockwise transfer
464 res = CAAddBlockOption(&pdu, info, data->remoteEndpoint, &options);
465 if (CA_STATUS_OK != res)
467 OIC_LOG(INFO, TAG, "to write block option has failed");
476 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
477 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
483 OIC_LOG(ERROR, TAG, "request or response info is empty");
487 CALogPDUInfo(pdu, data->remoteEndpoint);
489 OIC_LOG(DEBUG, TAG, "pdu to send :");
490 OIC_LOG_BUFFER(DEBUG, TAG, (uint8_t*)pdu->hdr, pdu->length);
492 res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
493 if (CA_STATUS_OK != res)
495 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
499 coap_delete_list(options);
500 coap_delete_pdu(pdu);
504 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
505 coap_delete_list(options);
506 coap_delete_pdu(pdu);
510 static CAResult_t CAProcessSendData(const CAData_t *data)
512 VERIFY_NON_NULL(data, TAG, "data");
513 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
515 CAResult_t res = CA_STATUS_FAILED;
517 CASendDataType_t type = data->type;
519 coap_pdu_t *pdu = NULL;
520 CAInfo_t *info = NULL;
521 coap_list_t *options = NULL;
522 coap_transport_type transport = coap_udp;
524 if (SEND_TYPE_UNICAST == type)
526 OIC_LOG(DEBUG,TAG,"Unicast message");
528 #ifdef ROUTING_GATEWAY
530 * When forwarding a packet, do not attempt retransmission as its the responsibility of
531 * packet originator node
533 bool skipRetransmission = false;
536 if (NULL != data->requestInfo)
538 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
540 info = &data->requestInfo->info;
541 #ifdef ROUTING_GATEWAY
542 skipRetransmission = data->requestInfo->info.skipRetransmission;
544 pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
545 &options, &transport);
547 else if (NULL != data->responseInfo)
549 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
551 info = &data->responseInfo->info;
552 #ifdef ROUTING_GATEWAY
553 skipRetransmission = data->responseInfo->info.skipRetransmission;
555 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
556 &options, &transport);
560 OIC_LOG(DEBUG, TAG, "request info, response info is empty");
561 return CA_STATUS_INVALID_PARAM;
564 // interface controller function call.
568 if (CAIsSupportedBlockwiseTransfer(data->remoteEndpoint->adapter))
570 // Blockwise transfer
573 CAResult_t res = CAAddBlockOption(&pdu, info,
574 data->remoteEndpoint,
576 if (CA_STATUS_OK != res)
578 OIC_LOG(INFO, TAG, "to write block option has failed");
579 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
580 coap_delete_list(options);
581 coap_delete_pdu(pdu);
587 CALogPDUInfo(pdu, data->remoteEndpoint);
589 res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
590 if (CA_STATUS_OK != res)
592 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
593 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
594 coap_delete_list(options);
595 coap_delete_pdu(pdu);
600 if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
602 OIC_LOG(INFO, TAG, "retransmission will be not worked");
606 #ifdef ROUTING_GATEWAY
607 if(!skipRetransmission)
610 // for retransmission
611 res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint,
612 pdu->hdr, pdu->length);
613 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
615 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
616 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
617 coap_delete_list(options);
618 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);
630 return CA_SEND_FAILED;
633 else if (SEND_TYPE_MULTICAST == type)
635 OIC_LOG(DEBUG,TAG,"Multicast message");
638 * If CoAP over TCP is enabled, the CoAP pdu wont be same for IP and other adapters.
639 * That's why we need to generate two pdu's, one for IP and second for other transports.
640 * Two possible cases we might have to split: a) when adapter is CA_DEFAULT_ADAPTER
641 * b) when one of the adapter is IP adapter(ex: CA_ADAPTER_IP | CA_ADAPTER_GATT_BTLE)
643 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER ||
644 (CA_ADAPTER_IP & data->remoteEndpoint->adapter &&
645 CA_ADAPTER_IP != data->remoteEndpoint->adapter))
647 if (data->remoteEndpoint->adapter == CA_DEFAULT_ADAPTER)
649 data->remoteEndpoint->adapter = CA_ALL_ADAPTERS ^ CA_ADAPTER_IP;
653 data->remoteEndpoint->adapter = data->remoteEndpoint->adapter ^ CA_ADAPTER_IP;
655 CAProcessMulticastData(data);
656 data->remoteEndpoint->adapter = CA_ADAPTER_IP;
657 CAProcessMulticastData(data);
661 CAProcessMulticastData(data);
664 CAProcessMulticastData(data);
671 #ifndef SINGLE_THREAD
672 static void CASendThreadProcess(void *threadData)
674 CAData_t *data = (CAData_t *) threadData;
675 CAProcessSendData(data);
680 * If a second message arrives with the same message ID, token and the other address
681 * family, drop it. Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
683 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
684 CAToken_t token, uint8_t tokenLength)
690 if (ep->adapter != CA_ADAPTER_IP)
694 if (!caglobals.ip.dualstack)
699 if (tokenLength > CA_MAX_TOKEN_LEN)
702 * If token length is more than CA_MAX_TOKEN_LEN,
703 * we compare the first CA_MAX_TOKEN_LEN bytes only.
705 tokenLength = CA_MAX_TOKEN_LEN;
709 CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
711 for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
713 CAHistoryItem_t *item = &(history->items[i]);
714 if (id == item->messageId && tokenLength == item->tokenLength
715 && memcmp(item->token, token, tokenLength) == 0)
717 if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
719 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
720 familyFlags & CA_IPV6 ? '6' : '4');
727 history->items[history->nextIndex].flags = familyFlags;
728 history->items[history->nextIndex].messageId = id;
729 if (token && tokenLength)
731 memcpy(history->items[history->nextIndex].token, token, tokenLength);
732 history->items[history->nextIndex].tokenLength = tokenLength;
735 if (++history->nextIndex >= HISTORYSIZE)
737 history->nextIndex = 0;
743 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
744 const void *data, uint32_t dataLen)
746 VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
747 VERIFY_NON_NULL_VOID(data, TAG, "data");
749 OIC_LOG(DEBUG, TAG, "received pdu data :");
750 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLen);
752 uint32_t code = CA_NOT_FOUND;
753 CAData_t *cadata = NULL;
755 coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
759 OIC_LOG(ERROR, TAG, "Parse PDU failed");
763 OIC_LOG_V(DEBUG, TAG, "code = %d", code);
764 if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
766 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
769 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
770 coap_delete_pdu(pdu);
776 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
779 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
780 coap_delete_pdu(pdu);
785 if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
787 OIC_LOG(INFO, TAG, "retransmission is not supported");
792 // for retransmission
793 void *retransmissionPdu = NULL;
794 CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
795 pdu->length, &retransmissionPdu);
797 // get token from saved data in retransmission list
798 if (retransmissionPdu && CA_EMPTY == code)
800 if (cadata->responseInfo)
802 CAInfo_t *info = &cadata->responseInfo->info;
803 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
804 info, &(sep->endpoint));
805 if (CA_STATUS_OK != res)
807 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
808 OICFree(info->token);
809 info->tokenLength = 0;
813 OICFree(retransmissionPdu);
817 cadata->type = SEND_TYPE_UNICAST;
820 CAProcessReceivedData(cadata);
823 if (CAIsSupportedBlockwiseTransfer(sep->endpoint.adapter))
825 CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
826 if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
828 OIC_LOG(DEBUG, TAG, "this message does not have block option");
829 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
833 CADestroyData(cadata, sizeof(CAData_t));
839 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
841 #endif // SINGLE_THREAD
843 coap_delete_pdu(pdu);
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);
1038 CASetErrorHandleCallback(CAErrorHandler);
1040 #ifndef SINGLE_THREAD
1041 // create thread pool
1042 CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1043 if (CA_STATUS_OK != res)
1045 OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1049 // send thread initialize
1050 res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1051 CASendThreadProcess, CADestroyData);
1052 if (CA_STATUS_OK != res)
1054 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1055 ca_thread_pool_free(g_threadPoolHandle);
1056 g_threadPoolHandle = NULL;
1060 // start send thread
1061 res = CAQueueingThreadStart(&g_sendThread);
1062 if (CA_STATUS_OK != res)
1064 OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1065 ca_thread_pool_free(g_threadPoolHandle);
1066 g_threadPoolHandle = NULL;
1067 CAQueueingThreadDestroy(&g_sendThread);
1071 // receive thread initialize
1072 res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1073 CAReceiveThreadProcess, CADestroyData);
1074 if (CA_STATUS_OK != res)
1076 OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1077 ca_thread_pool_free(g_threadPoolHandle);
1078 g_threadPoolHandle = NULL;
1079 CAQueueingThreadDestroy(&g_sendThread);
1083 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1084 // start receive thread
1085 res = CAQueueingThreadStart(&g_receiveThread);
1086 if (CA_STATUS_OK != res)
1088 OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1089 ca_thread_pool_free(g_threadPoolHandle);
1090 g_threadPoolHandle = NULL;
1091 CAQueueingThreadDestroy(&g_sendThread);
1092 CAQueueingThreadDestroy(&g_receiveThread);
1095 #endif // SINGLE_HANDLE
1097 // retransmission initialize
1098 res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1099 CASendUnicastData, CATimeoutCallback, NULL);
1100 if (CA_STATUS_OK != res)
1102 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1103 ca_thread_pool_free(g_threadPoolHandle);
1104 g_threadPoolHandle = NULL;
1105 CAQueueingThreadDestroy(&g_sendThread);
1106 CAQueueingThreadDestroy(&g_receiveThread);
1111 // block-wise transfer initialize
1112 res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1113 if (CA_STATUS_OK != res)
1115 OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1116 ca_thread_pool_free(g_threadPoolHandle);
1117 g_threadPoolHandle = NULL;
1118 CAQueueingThreadDestroy(&g_sendThread);
1119 CAQueueingThreadDestroy(&g_receiveThread);
1120 CARetransmissionDestroy(&g_retransmissionContext);
1125 // start retransmission
1126 res = CARetransmissionStart(&g_retransmissionContext);
1127 if (CA_STATUS_OK != res)
1129 OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1130 ca_thread_pool_free(g_threadPoolHandle);
1131 g_threadPoolHandle = NULL;
1132 CAQueueingThreadDestroy(&g_sendThread);
1133 CAQueueingThreadDestroy(&g_receiveThread);
1134 CARetransmissionDestroy(&g_retransmissionContext);
1138 // initialize interface adapters by controller
1139 CAInitializeAdapters(g_threadPoolHandle);
1141 // retransmission initialize
1142 CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1143 CATimeoutCallback, NULL);
1144 if (CA_STATUS_OK != res)
1146 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1150 CAInitializeAdapters();
1151 #endif // SINGLE_THREAD
1153 return CA_STATUS_OK;
1156 void CATerminateMessageHandler()
1158 #ifndef SINGLE_THREAD
1159 CATransportAdapter_t connType;
1160 u_arraylist_t *list = CAGetSelectedNetworkList();
1161 uint32_t length = u_arraylist_length(list);
1164 for (i = 0; i < length; i++)
1166 void* ptrType = u_arraylist_get(list, i);
1168 if (NULL == ptrType)
1173 connType = *(CATransportAdapter_t *)ptrType;
1174 CAStopAdapter(connType);
1177 // stop retransmission
1178 if (NULL != g_retransmissionContext.threadMutex)
1180 CARetransmissionStop(&g_retransmissionContext);
1184 // delete thread data
1185 if (NULL != g_sendThread.threadMutex)
1187 CAQueueingThreadStop(&g_sendThread);
1191 // delete thread data
1192 if (NULL != g_receiveThread.threadMutex)
1194 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1195 CAQueueingThreadStop(&g_receiveThread);
1199 // destroy thread pool
1200 if (NULL != g_threadPoolHandle)
1202 ca_thread_pool_free(g_threadPoolHandle);
1203 g_threadPoolHandle = NULL;
1207 CATerminateBlockWiseTransfer();
1209 CARetransmissionDestroy(&g_retransmissionContext);
1210 CAQueueingThreadDestroy(&g_sendThread);
1211 CAQueueingThreadDestroy(&g_receiveThread);
1213 // terminate interface adapters by controller
1214 CATerminateAdapters();
1216 // terminate interface adapters by controller
1217 CATerminateAdapters();
1219 // stop retransmission
1220 CARetransmissionStop(&g_retransmissionContext);
1221 CARetransmissionDestroy(&g_retransmissionContext);
1222 #endif // SINGLE_THREAD
1225 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1227 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1228 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1230 OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1233 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1235 OIC_LOG(DEBUG, TAG, "pdu header data :");
1236 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) pdu->hdr, pdu->length);
1241 OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1243 OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1245 OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1247 OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1248 pdu->hdr->coap_hdr_udp_t.token_length);
1252 static void CALogPayloadInfo(CAInfo_t *info)
1258 for (uint32_t i = 0; i < info->numOptions; i++)
1260 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1262 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1268 OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1274 OIC_LOG(DEBUG, TAG, "token:");
1275 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1278 OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1282 OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1286 void CAErrorHandler(const CAEndpoint_t *endpoint,
1287 const void *data, uint32_t dataLen,
1290 OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1292 #ifndef SINGLE_THREAD
1293 VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1294 VERIFY_NON_NULL_VOID(data, TAG, "data");
1296 uint32_t code = CA_NOT_FOUND;
1297 //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1299 coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1302 OIC_LOG(ERROR, TAG, "Parse PDU failed");
1306 CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1309 OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1310 coap_delete_pdu(pdu);
1314 cadata->errorInfo->result = result;
1316 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1317 coap_delete_pdu(pdu);
1320 OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1324 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1326 OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1327 #ifndef SINGLE_THREAD
1328 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1331 OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1335 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1338 OIC_LOG(ERROR, TAG, "endpoint clone failed");
1343 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1346 OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1352 CAResult_t res = CACloneInfo(info, &errorInfo->info);
1353 if (CA_STATUS_OK != res)
1355 OIC_LOG(ERROR, TAG, "info clone failed");
1362 errorInfo->result = result;
1363 cadata->remoteEndpoint = ep;
1364 cadata->errorInfo = errorInfo;
1365 cadata->dataType = CA_ERROR_DATA;
1367 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1369 OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");