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 CAProcessSendData(const CAData_t *data)
399 VERIFY_NON_NULL(data, TAG, "data");
400 VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
402 CAResult_t res = CA_STATUS_FAILED;
404 CASendDataType_t type = data->type;
406 coap_pdu_t *pdu = NULL;
407 CAInfo_t *info = NULL;
408 coap_list_t *options = NULL;
409 coap_transport_type transport;
411 if (SEND_TYPE_UNICAST == type)
413 OIC_LOG(DEBUG,TAG,"Unicast message");
414 #ifdef ROUTING_GATEWAY
416 * When forwarding a packet, do not attempt retransmission as its the responsibility of
417 * packet originator node
419 bool skipRetransmission = false;
422 if (NULL != data->requestInfo)
424 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
426 info = &data->requestInfo->info;
427 #ifdef ROUTING_GATEWAY
428 skipRetransmission = data->requestInfo->info.skipRetransmission;
430 pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
431 &options, &transport);
433 else if (NULL != data->responseInfo)
435 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
437 info = &data->responseInfo->info;
438 #ifdef ROUTING_GATEWAY
439 skipRetransmission = data->responseInfo->info.skipRetransmission;
441 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
442 &options, &transport);
446 OIC_LOG(DEBUG, TAG, "request info, response info is empty");
447 return CA_STATUS_INVALID_PARAM;
450 // interface controller function call.
454 if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
456 && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
460 // Blockwise transfer
463 CAResult_t res = CAAddBlockOption(&pdu, info,
464 data->remoteEndpoint,
466 if (CA_STATUS_OK != res)
468 OIC_LOG(INFO, TAG, "to write block option has failed");
469 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
470 coap_delete_list(options);
471 coap_delete_pdu(pdu);
477 CALogPDUInfo(pdu, data->remoteEndpoint);
479 res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
480 if (CA_STATUS_OK != res)
482 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
483 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
484 coap_delete_list(options);
485 coap_delete_pdu(pdu);
490 if (CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter))
492 OIC_LOG(INFO, TAG, "retransmission will be not worked");
496 #ifdef ROUTING_GATEWAY
497 if(!skipRetransmission)
500 // for retransmission
501 res = CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint,
502 pdu->hdr, pdu->length);
503 if ((CA_STATUS_OK != res) && (CA_NOT_SUPPORTED != res))
505 //when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
506 OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
507 coap_delete_list(options);
508 coap_delete_pdu(pdu);
513 coap_delete_list(options);
514 coap_delete_pdu(pdu);
518 OIC_LOG(ERROR,TAG,"Failed to generate unicast PDU");
519 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
520 return CA_SEND_FAILED;
523 else if (SEND_TYPE_MULTICAST == type)
525 OIC_LOG(DEBUG,TAG,"Multicast message");
526 if (NULL != data->requestInfo)
528 OIC_LOG(DEBUG, TAG, "requestInfo is available..");
530 info = &data->requestInfo->info;
531 pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
536 if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
538 && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
542 // Blockwise transfer
543 CAResult_t res = CAAddBlockOption(&pdu, info,
544 data->remoteEndpoint,
546 if (CA_STATUS_OK != res)
548 OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
549 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
550 coap_delete_list(options);
551 coap_delete_pdu(pdu);
559 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
560 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
561 return CA_SEND_FAILED;
564 else if (NULL != data->responseInfo)
566 OIC_LOG(DEBUG, TAG, "responseInfo is available..");
568 info = &data->responseInfo->info;
569 pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
570 &options, &transport);
575 if (CA_ADAPTER_GATT_BTLE != data->remoteEndpoint->adapter
577 && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
581 // Blockwise transfer
584 CAResult_t res = CAAddBlockOption(&pdu, info,
585 data->remoteEndpoint,
587 if (CA_STATUS_OK != res)
589 OIC_LOG(INFO, TAG, "to write block option has failed");
590 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
591 coap_delete_list(options);
592 coap_delete_pdu(pdu);
601 OIC_LOG(ERROR,TAG,"Failed to generate multicast PDU");
602 CASendErrorInfo(data->remoteEndpoint, info, CA_SEND_FAILED);
603 return CA_SEND_FAILED;
608 OIC_LOG(ERROR, TAG, "request or response info is empty");
609 return CA_SEND_FAILED;
612 CALogPDUInfo(pdu, data->remoteEndpoint);
614 OIC_LOG(DEBUG, TAG, "pdu to send :");
615 OIC_LOG_BUFFER(DEBUG, TAG, (uint8_t*)pdu->hdr, pdu->length);
617 res = CASendMulticastData(data->remoteEndpoint, pdu->hdr, pdu->length);
618 if (CA_STATUS_OK != res)
620 OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
621 CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
622 coap_delete_list(options);
623 coap_delete_pdu(pdu);
627 coap_delete_list(options);
628 coap_delete_pdu(pdu);
634 #ifndef SINGLE_THREAD
635 static void CASendThreadProcess(void *threadData)
637 CAData_t *data = (CAData_t *) threadData;
638 CAProcessSendData(data);
643 * If a second message arrives with the same message ID, token and the other address
644 * family, drop it. Typically, IPv6 beats IPv4, so the IPv4 message is dropped.
646 static bool CADropSecondMessage(CAHistory_t *history, const CAEndpoint_t *ep, uint16_t id,
647 CAToken_t token, uint8_t tokenLength)
653 if (ep->adapter != CA_ADAPTER_IP)
657 if (!caglobals.ip.dualstack)
662 if (tokenLength > CA_MAX_TOKEN_LEN)
665 * If token length is more than CA_MAX_TOKEN_LEN,
666 * we compare the first CA_MAX_TOKEN_LEN bytes only.
668 tokenLength = CA_MAX_TOKEN_LEN;
672 CATransportFlags_t familyFlags = ep->flags & CA_IPFAMILY_MASK;
674 for (size_t i = 0; i < sizeof(history->items) / sizeof(history->items[0]); i++)
676 CAHistoryItem_t *item = &(history->items[i]);
677 if (id == item->messageId && tokenLength == item->tokenLength
678 && memcmp(item->token, token, tokenLength) == 0)
680 if ((familyFlags ^ item->flags) == CA_IPFAMILY_MASK)
682 OIC_LOG_V(INFO, TAG, "IPv%c duplicate message ignored",
683 familyFlags & CA_IPV6 ? '6' : '4');
690 history->items[history->nextIndex].flags = familyFlags;
691 history->items[history->nextIndex].messageId = id;
692 if (token && tokenLength)
694 memcpy(history->items[history->nextIndex].token, token, tokenLength);
695 history->items[history->nextIndex].tokenLength = tokenLength;
698 if (++history->nextIndex >= HISTORYSIZE)
700 history->nextIndex = 0;
706 static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
707 const void *data, uint32_t dataLen)
709 VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
710 VERIFY_NON_NULL_VOID(data, TAG, "data");
712 OIC_LOG(DEBUG, TAG, "received pdu data :");
713 OIC_LOG_BUFFER(DEBUG, TAG, data, dataLen);
715 uint32_t code = CA_NOT_FOUND;
716 CAData_t *cadata = NULL;
718 coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code,
722 OIC_LOG(ERROR, TAG, "Parse PDU failed");
726 OIC_LOG_V(DEBUG, TAG, "code = %d", code);
727 if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
729 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_REQUEST_DATA);
732 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
733 coap_delete_pdu(pdu);
739 cadata = CAGenerateHandlerData(&(sep->endpoint), &(sep->identity), pdu, CA_RESPONSE_DATA);
742 OIC_LOG(ERROR, TAG, "CAReceivedPacketCallback, CAGenerateHandlerData failed!");
743 coap_delete_pdu(pdu);
748 if (CAIsSupportedCoAPOverTCP(sep->endpoint.adapter))
750 OIC_LOG(INFO, TAG, "retransmission is not supported");
755 // for retransmission
756 void *retransmissionPdu = NULL;
757 CARetransmissionReceivedData(&g_retransmissionContext, cadata->remoteEndpoint, pdu->hdr,
758 pdu->length, &retransmissionPdu);
760 // get token from saved data in retransmission list
761 if (retransmissionPdu && CA_EMPTY == code)
763 if (cadata->responseInfo)
765 CAInfo_t *info = &cadata->responseInfo->info;
766 CAResult_t res = CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu,
767 info, &(sep->endpoint));
768 if (CA_STATUS_OK != res)
770 OIC_LOG(ERROR, TAG, "fail to get Token from retransmission list");
771 OICFree(info->token);
772 info->tokenLength = 0;
776 OICFree(retransmissionPdu);
780 cadata->type = SEND_TYPE_UNICAST;
783 CAProcessReceivedData(cadata);
786 if (CA_ADAPTER_GATT_BTLE != sep->endpoint.adapter
788 && !CAIsSupportedCoAPOverTCP(sep->endpoint.adapter)
792 CAResult_t res = CAReceiveBlockWiseData(pdu, &(sep->endpoint), cadata, dataLen);
793 if (CA_NOT_SUPPORTED == res || CA_REQUEST_TIMEOUT == res)
795 OIC_LOG(ERROR, TAG, "this message does not have block option");
796 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
800 CADestroyData(cadata, sizeof(CAData_t));
806 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
808 #endif // SINGLE_THREAD
810 coap_delete_pdu(pdu);
813 static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
818 if (g_nwMonitorHandler)
820 g_nwMonitorHandler(info, status);
824 void CAHandleRequestResponseCallbacks()
828 CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
831 // parse the data and call the callbacks.
835 ca_mutex_lock(g_receiveThread.threadMutex);
837 u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
839 ca_mutex_unlock(g_receiveThread.threadMutex);
841 if (NULL == item || NULL == item->msg)
847 CAData_t *td = (CAData_t *) item->msg;
849 if (td->requestInfo && g_requestHandler)
851 OIC_LOG_V(DEBUG, TAG, "request callback : %d", td->requestInfo->info.numOptions);
852 g_requestHandler(td->remoteEndpoint, td->requestInfo);
854 else if (td->responseInfo && g_responseHandler)
856 OIC_LOG_V(DEBUG, TAG, "response callback : %d", td->responseInfo->info.numOptions);
857 g_responseHandler(td->remoteEndpoint, td->responseInfo);
859 else if (td->errorInfo && g_errorHandler)
861 OIC_LOG_V(DEBUG, TAG, "error callback error: %d", td->errorInfo->result);
862 g_errorHandler(td->remoteEndpoint, td->errorInfo);
865 CADestroyData(item->msg, sizeof(CAData_t));
868 #endif // SINGLE_HANDLE
869 #endif // SINGLE_THREAD
872 static CAData_t* CAPrepareSendData(const CAEndpoint_t *endpoint, const void *sendData,
873 CADataType_t dataType)
875 OIC_LOG(DEBUG, TAG, "CAPrepareSendData IN");
877 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
880 OIC_LOG(ERROR, TAG, "memory allocation failed");
884 if(CA_REQUEST_DATA == dataType)
886 // clone request info
887 CARequestInfo_t *request = CACloneRequestInfo((CARequestInfo_t *)sendData);
891 OIC_LOG(ERROR, TAG, "CACloneRequestInfo failed");
896 cadata->type = request->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
897 cadata->requestInfo = request;
899 else if(CA_RESPONSE_DATA == dataType)
901 // clone response info
902 CAResponseInfo_t *response = CACloneResponseInfo((CAResponseInfo_t *)sendData);
906 OIC_LOG(ERROR, TAG, "CACloneResponseInfo failed");
911 cadata->type = response->isMulticast ? SEND_TYPE_MULTICAST : SEND_TYPE_UNICAST;
912 cadata->responseInfo = response;
916 OIC_LOG(ERROR, TAG, "CAPrepareSendData unknown data type");
921 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
924 OIC_LOG(ERROR, TAG, "endpoint clone failed");
925 CADestroyData(cadata, sizeof(CAData_t));
929 cadata->remoteEndpoint = ep;
930 cadata->dataType = dataType;
934 CAResult_t CADetachSendMessage(const CAEndpoint_t *endpoint, const void *sendMsg,
935 CADataType_t dataType)
937 VERIFY_NON_NULL(endpoint, TAG, "endpoint");
938 VERIFY_NON_NULL(sendMsg, TAG, "sendMsg");
940 if (false == CAIsSelectedNetworkAvailable())
942 return CA_STATUS_FAILED;
946 // If max retransmission queue is reached, then don't handle new request
947 if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
949 OIC_LOG(ERROR, TAG, "max RT queue size reached!");
950 return CA_SEND_FAILED;
954 CAData_t *data = CAPrepareSendData(endpoint, sendMsg, dataType);
957 OIC_LOG(ERROR, TAG, "CAPrepareSendData failed");
958 return CA_MEMORY_ALLOC_FAILED;
962 CAResult_t result = CAProcessSendData(data);
963 if(CA_STATUS_OK != result)
965 OIC_LOG(ERROR, TAG, "CAProcessSendData failed");
966 CADestroyData(data, sizeof(CAData_t));
970 CADestroyData(data, sizeof(CAData_t));
973 if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
975 && !CAIsSupportedCoAPOverTCP(data->remoteEndpoint->adapter)
980 CAResult_t res = CASendBlockWiseData(data);
981 if(CA_NOT_SUPPORTED == res)
983 OIC_LOG(DEBUG, TAG, "normal msg will be sent");
984 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
989 CADestroyData(data, sizeof(CAData_t));
996 CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
998 #endif // SINGLE_THREAD
1000 return CA_STATUS_OK;
1003 CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
1004 uint8_t tokenLength, const CAHeaderOption_t *options,
1012 return CA_NOT_SUPPORTED;
1015 void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
1016 CAErrorCallback errorHandler)
1018 g_requestHandler = ReqHandler;
1019 g_responseHandler = RespHandler;
1020 g_errorHandler = errorHandler;
1023 void CASetNetworkMonitorCallback(CANetworkMonitorCallback nwMonitorHandler)
1025 g_nwMonitorHandler = nwMonitorHandler;
1028 CAResult_t CAInitializeMessageHandler()
1030 CASetPacketReceivedCallback(CAReceivedPacketCallback);
1032 CASetNetworkChangeCallback(CANetworkChangedCallback);
1033 CASetErrorHandleCallback(CAErrorHandler);
1035 #ifndef SINGLE_THREAD
1036 // create thread pool
1037 CAResult_t res = ca_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
1038 if (CA_STATUS_OK != res)
1040 OIC_LOG(ERROR, TAG, "thread pool initialize error.");
1044 // send thread initialize
1045 res = CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle,
1046 CASendThreadProcess, CADestroyData);
1047 if (CA_STATUS_OK != res)
1049 OIC_LOG(ERROR, TAG, "Failed to Initialize send queue thread");
1050 ca_thread_pool_free(g_threadPoolHandle);
1051 g_threadPoolHandle = NULL;
1055 // start send thread
1056 res = CAQueueingThreadStart(&g_sendThread);
1057 if (CA_STATUS_OK != res)
1059 OIC_LOG(ERROR, TAG, "thread start error(send thread).");
1060 ca_thread_pool_free(g_threadPoolHandle);
1061 g_threadPoolHandle = NULL;
1062 CAQueueingThreadDestroy(&g_sendThread);
1066 // receive thread initialize
1067 res = CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle,
1068 CAReceiveThreadProcess, CADestroyData);
1069 if (CA_STATUS_OK != res)
1071 OIC_LOG(ERROR, TAG, "Failed to Initialize receive queue thread");
1072 ca_thread_pool_free(g_threadPoolHandle);
1073 g_threadPoolHandle = NULL;
1074 CAQueueingThreadDestroy(&g_sendThread);
1078 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1079 // start receive thread
1080 res = CAQueueingThreadStart(&g_receiveThread);
1081 if (CA_STATUS_OK != res)
1083 OIC_LOG(ERROR, TAG, "thread start error(receive thread).");
1084 ca_thread_pool_free(g_threadPoolHandle);
1085 g_threadPoolHandle = NULL;
1086 CAQueueingThreadDestroy(&g_sendThread);
1087 CAQueueingThreadDestroy(&g_receiveThread);
1090 #endif // SINGLE_HANDLE
1092 // retransmission initialize
1093 res = CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle,
1094 CASendUnicastData, CATimeoutCallback, NULL);
1095 if (CA_STATUS_OK != res)
1097 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1098 ca_thread_pool_free(g_threadPoolHandle);
1099 g_threadPoolHandle = NULL;
1100 CAQueueingThreadDestroy(&g_sendThread);
1101 CAQueueingThreadDestroy(&g_receiveThread);
1106 // block-wise transfer initialize
1107 res = CAInitializeBlockWiseTransfer(CAAddDataToSendThread, CAAddDataToReceiveThread);
1108 if (CA_STATUS_OK != res)
1110 OIC_LOG(ERROR, TAG, "Failed to Initialize BlockWiseTransfer.");
1111 ca_thread_pool_free(g_threadPoolHandle);
1112 g_threadPoolHandle = NULL;
1113 CAQueueingThreadDestroy(&g_sendThread);
1114 CAQueueingThreadDestroy(&g_receiveThread);
1115 CARetransmissionDestroy(&g_retransmissionContext);
1120 // start retransmission
1121 res = CARetransmissionStart(&g_retransmissionContext);
1122 if (CA_STATUS_OK != res)
1124 OIC_LOG(ERROR, TAG, "thread start error(retransmission thread).");
1125 ca_thread_pool_free(g_threadPoolHandle);
1126 g_threadPoolHandle = NULL;
1127 CAQueueingThreadDestroy(&g_sendThread);
1128 CAQueueingThreadDestroy(&g_receiveThread);
1129 CARetransmissionDestroy(&g_retransmissionContext);
1133 // initialize interface adapters by controller
1134 CAInitializeAdapters(g_threadPoolHandle);
1136 // retransmission initialize
1137 CAResult_t res = CARetransmissionInitialize(&g_retransmissionContext, NULL, CASendUnicastData,
1138 CATimeoutCallback, NULL);
1139 if (CA_STATUS_OK != res)
1141 OIC_LOG(ERROR, TAG, "Failed to Initialize Retransmission.");
1145 CAInitializeAdapters();
1146 #endif // SINGLE_THREAD
1148 return CA_STATUS_OK;
1151 void CATerminateMessageHandler()
1153 #ifndef SINGLE_THREAD
1154 CATransportAdapter_t connType;
1155 u_arraylist_t *list = CAGetSelectedNetworkList();
1156 uint32_t length = u_arraylist_length(list);
1159 for (i = 0; i < length; i++)
1161 void* ptrType = u_arraylist_get(list, i);
1163 if (NULL == ptrType)
1168 connType = *(CATransportAdapter_t *)ptrType;
1169 CAStopAdapter(connType);
1172 // stop retransmission
1173 if (NULL != g_retransmissionContext.threadMutex)
1175 CARetransmissionStop(&g_retransmissionContext);
1179 // delete thread data
1180 if (NULL != g_sendThread.threadMutex)
1182 CAQueueingThreadStop(&g_sendThread);
1186 // delete thread data
1187 if (NULL != g_receiveThread.threadMutex)
1189 #ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
1190 CAQueueingThreadStop(&g_receiveThread);
1194 // destroy thread pool
1195 if (NULL != g_threadPoolHandle)
1197 ca_thread_pool_free(g_threadPoolHandle);
1198 g_threadPoolHandle = NULL;
1202 CATerminateBlockWiseTransfer();
1204 CARetransmissionDestroy(&g_retransmissionContext);
1205 CAQueueingThreadDestroy(&g_sendThread);
1206 CAQueueingThreadDestroy(&g_receiveThread);
1208 // terminate interface adapters by controller
1209 CATerminateAdapters();
1211 // terminate interface adapters by controller
1212 CATerminateAdapters();
1214 // stop retransmission
1215 CARetransmissionStop(&g_retransmissionContext);
1216 CARetransmissionDestroy(&g_retransmissionContext);
1217 #endif // SINGLE_THREAD
1220 void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
1222 VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
1223 VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
1225 OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
1228 if (CAIsSupportedCoAPOverTCP(endpoint->adapter))
1230 OIC_LOG(DEBUG, TAG, "pdu header data :");
1231 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) pdu->hdr, pdu->length);
1236 OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->coap_hdr_udp_t.type);
1238 OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->coap_hdr_udp_t.code);
1240 OIC_LOG(DEBUG, TAG, "PDU Maker - token :");
1242 OIC_LOG_BUFFER(DEBUG, TAG, pdu->hdr->coap_hdr_udp_t.token,
1243 pdu->hdr->coap_hdr_udp_t.token_length);
1247 static void CALogPayloadInfo(CAInfo_t *info)
1253 for (uint32_t i = 0; i < info->numOptions; i++)
1255 OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
1257 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
1263 OIC_LOG_V(DEBUG, TAG, "payload: %p(%zu)", info->payload,
1269 OIC_LOG(DEBUG, TAG, "token:");
1270 OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
1273 OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
1277 OIC_LOG(DEBUG, TAG, "info is NULL, cannot output log data");
1281 void CAErrorHandler(const CAEndpoint_t *endpoint,
1282 const void *data, uint32_t dataLen,
1285 OIC_LOG(DEBUG, TAG, "CAErrorHandler IN");
1287 #ifndef SINGLE_THREAD
1288 VERIFY_NON_NULL_VOID(endpoint, TAG, "remoteEndpoint");
1289 VERIFY_NON_NULL_VOID(data, TAG, "data");
1291 uint32_t code = CA_NOT_FOUND;
1292 //Do not free remoteEndpoint and data. Currently they will be freed in data thread
1294 coap_pdu_t *pdu = (coap_pdu_t *)CAParsePDU((const char *)data, dataLen, &code, endpoint);
1297 OIC_LOG(ERROR, TAG, "Parse PDU failed");
1301 CAData_t *cadata = CAGenerateHandlerData(endpoint, NULL, pdu, CA_ERROR_DATA);
1304 OIC_LOG(ERROR, TAG, "CAErrorHandler, CAGenerateHandlerData failed!");
1305 coap_delete_pdu(pdu);
1309 cadata->errorInfo->result = result;
1311 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1312 coap_delete_pdu(pdu);
1315 OIC_LOG(DEBUG, TAG, "CAErrorHandler OUT");
1319 static void CASendErrorInfo(const CAEndpoint_t *endpoint, const CAInfo_t *info, CAResult_t result)
1321 OIC_LOG(DEBUG, TAG, "CASendErrorInfo IN");
1322 #ifndef SINGLE_THREAD
1323 CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
1326 OIC_LOG(ERROR, TAG, "cadata memory allocation failed");
1330 CAEndpoint_t* ep = CACloneEndpoint(endpoint);
1333 OIC_LOG(ERROR, TAG, "endpoint clone failed");
1338 CAErrorInfo_t *errorInfo = (CAErrorInfo_t *)OICCalloc(1, sizeof (CAErrorInfo_t));
1341 OIC_LOG(ERROR, TAG, "errorInfo memory allocation failed");
1347 CAResult_t res = CACloneInfo(info, &errorInfo->info);
1348 if (CA_STATUS_OK != res)
1350 OIC_LOG(ERROR, TAG, "info clone failed");
1357 errorInfo->result = result;
1358 cadata->remoteEndpoint = ep;
1359 cadata->errorInfo = errorInfo;
1360 cadata->dataType = CA_ERROR_DATA;
1362 CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
1364 OIC_LOG(DEBUG, TAG, "CASendErrorInfo OUT");