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 ******************************************************************/
21 // Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose
22 // definitions that may otherwise be skipped. Skipping can cause implicit
23 // declaration warnings and/or bugs and subtle problems in code execution.
24 // For glibc information on feature test macros,
25 // Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
27 // This file requires #define use due to random()
28 // For details on compatibility and glibc support,
29 // Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
30 #define _DEFAULT_SOURCE
32 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
33 // causes header files to expose definitions
34 // corresponding to the POSIX.1b, Real-time extensions
35 // (IEEE Std 1003.1b-1993) specification
37 // For this specific file, see use of clock_gettime,
38 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
39 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
40 #ifndef _POSIX_C_SOURCE
41 #define _POSIX_C_SOURCE 200809L
52 #ifdef HAVE_SYS_TIME_H
56 #include <sys/timeb.h>
63 #if defined(__ANDROID__)
64 #include <linux/time.h>
67 #include "caretransmission.h"
68 #include "caremotehandler.h"
69 #include "caprotocolmessage.h"
70 #include "oic_malloc.h"
75 #define TAG "OIC_CA_RETRANS"
79 uint64_t timeStamp; /**< last sent time. microseconds */
81 uint64_t timeout; /**< timeout value. microseconds */
83 uint8_t triedCount; /**< retransmission count */
84 uint16_t messageId; /**< coap PDU message id */
85 CAEndpoint_t *endpoint; /**< remote endpoint */
86 void *pdu; /**< coap PDU */
87 uint32_t size; /**< coap PDU size */
88 } CARetransmissionData_t;
90 static const uint64_t USECS_PER_SEC = 1000000;
91 static const uint64_t MSECS_PER_SEC = 1000;
95 * @brief timeout value is
96 * between DEFAULT_ACK_TIMEOUT_SEC and
97 * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
98 * DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
99 * @return microseconds.
101 static uint64_t CAGetTimeoutValue()
103 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
107 CAResult_t CARetransmissionStart(CARetransmission_t *context)
111 OIC_LOG(ERROR, TAG, "context is empty");
112 return CA_STATUS_INVALID_PARAM;
115 if (NULL == context->threadPool)
117 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
118 return CA_STATUS_INVALID_PARAM;
121 CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
124 if (CA_STATUS_OK != res)
126 OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
135 * @brief check timeout routine
136 * @param currentTime [IN]microseconds
137 * @param retData [IN]retransmission data
138 * @return true if the timeout period has elapsed, false otherwise
140 static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
142 #ifndef SINGLE_THREAD
143 // #1. calculate timeout
144 uint32_t milliTimeoutValue = retData->timeout * 0.001;
145 uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
147 if (currentTime >= retData->timeStamp + timeout)
149 OIC_LOG_V(DEBUG, TAG, "%llu microseconds time out!!, tried count(%d)",
150 timeout, retData->triedCount);
154 // #1. calculate timeout
155 uint64_t timeOut = (2 << retData->triedCount) * 1000000;
157 if (currentTime >= retData->timeStamp + timeOut)
159 OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
160 (2 << retData->triedCount), retData->triedCount);
167 static void CACheckRetransmissionList(CARetransmission_t *context)
171 OIC_LOG(ERROR, TAG, "context is null");
176 ca_mutex_lock(context->threadMutex);
179 uint32_t len = u_arraylist_length(context->dataList);
181 for (i = 0; i < len; i++)
183 CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
190 uint64_t currentTime = OICGetCurrentTime(TIME_IN_US);
192 if (CACheckTimeout(currentTime, retData))
194 // #2. if time's up, send the data.
195 if (NULL != context->dataSendMethod)
197 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
199 context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
202 // #3. increase the retransmission count and update timestamp.
203 retData->timeStamp = currentTime;
204 retData->triedCount++;
207 // #4. if tried count is max, remove the retransmission data from list.
208 if (retData->triedCount >= context->config.tryingCount)
210 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
211 if (NULL == removedData)
213 OIC_LOG(ERROR, TAG, "Removed data is NULL");
215 ca_mutex_unlock(context->threadMutex);
218 OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
219 "msgid=%d", removedData->messageId);
221 // callback for retransmit timeout
222 if (NULL != context->timeoutCallback)
224 context->timeoutCallback(removedData->endpoint, removedData->pdu,
228 CAFreeEndpoint(removedData->endpoint);
229 OICFree(removedData->pdu);
231 OICFree(removedData);
233 // modify loop value.
234 len = u_arraylist_length(context->dataList);
240 ca_mutex_unlock(context->threadMutex);
243 void CARetransmissionBaseRoutine(void *threadValue)
245 OIC_LOG(DEBUG, TAG, "retransmission main thread start");
247 CARetransmission_t *context = (CARetransmission_t *) threadValue;
251 OIC_LOG(ERROR, TAG, "thread data passing error");
257 if (true == context->isStop)
259 OIC_LOG(DEBUG, TAG, "thread stopped");
262 CACheckRetransmissionList(context);
265 while (!context->isStop)
268 ca_mutex_lock(context->threadMutex);
270 if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
272 // if list is empty, thread will wait
273 OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
276 ca_cond_wait(context->threadCond, context->threadMutex);
278 OIC_LOG(DEBUG, TAG, "wake up..");
280 else if (!context->isStop)
282 // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
283 OIC_LOG_V(DEBUG, TAG, "wait..(%lld)microseconds",
284 RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
287 uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
288 ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
292 // we are stopping, so we want to unlock and finish stopping
296 ca_mutex_unlock(context->threadMutex);
304 CACheckRetransmissionList(context);
307 ca_mutex_lock(context->threadMutex);
308 ca_cond_signal(context->threadCond);
309 ca_mutex_unlock(context->threadMutex);
312 OIC_LOG(DEBUG, TAG, "retransmission main thread end");
316 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
317 ca_thread_pool_t handle,
318 CADataSendMethod_t retransmissionSendMethod,
319 CATimeoutCallback_t timeoutCallback,
320 CARetransmissionConfig_t* config)
324 OIC_LOG(ERROR, TAG, "thread instance is empty");
325 return CA_STATUS_INVALID_PARAM;
327 #ifndef SINGLE_THREAD
330 OIC_LOG(ERROR, TAG, "thread pool handle is empty");
331 return CA_STATUS_INVALID_PARAM;
334 OIC_LOG(DEBUG, TAG, "thread initialize");
336 memset(context, 0, sizeof(CARetransmission_t));
338 CARetransmissionConfig_t cfg = { .supportType = DEFAULT_RETRANSMISSION_TYPE,
339 .tryingCount = DEFAULT_RETRANSMISSION_COUNT };
346 // set send thread data
347 context->threadPool = handle;
348 context->threadMutex = ca_mutex_new();
349 context->threadCond = ca_cond_new();
350 context->dataSendMethod = retransmissionSendMethod;
351 context->timeoutCallback = timeoutCallback;
352 context->config = cfg;
353 context->isStop = false;
354 context->dataList = u_arraylist_create();
359 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
360 const CAEndpoint_t *endpoint,
361 const void *pdu, uint32_t size)
363 if (NULL == context || NULL == endpoint || NULL == pdu)
365 OIC_LOG(ERROR, TAG, "invalid parameter");
366 return CA_STATUS_INVALID_PARAM;
369 // #0. check support transport type
370 if (!(context->config.supportType & endpoint->adapter))
372 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
373 return CA_NOT_SUPPORTED;
376 // #1. check PDU method type and get message id.
377 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
378 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
380 OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d, msgid=%d", type, messageId);
382 if (CA_MSG_CONFIRM != type)
384 OIC_LOG(DEBUG, TAG, "not supported message type");
385 return CA_NOT_SUPPORTED;
388 // create retransmission data
389 CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
390 1, sizeof(CARetransmissionData_t));
394 OIC_LOG(ERROR, TAG, "memory error");
395 return CA_MEMORY_ALLOC_FAILED;
399 void *pduData = (void *) OICMalloc(size);
403 OIC_LOG(ERROR, TAG, "memory error");
404 return CA_MEMORY_ALLOC_FAILED;
406 memcpy(pduData, pdu, size);
408 // clone remote endpoint
409 CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
410 if (NULL == remoteEndpoint)
414 OIC_LOG(ERROR, TAG, "memory error");
415 return CA_MEMORY_ALLOC_FAILED;
418 // #2. add additional information. (time stamp, retransmission count...)
419 retData->timeStamp = OICGetCurrentTime(TIME_IN_US);
420 #ifndef SINGLE_THREAD
421 retData->timeout = CAGetTimeoutValue();
423 retData->triedCount = 0;
424 retData->messageId = messageId;
425 retData->endpoint = remoteEndpoint;
426 retData->pdu = pduData;
427 retData->size = size;
428 #ifndef SINGLE_THREAD
430 ca_mutex_lock(context->threadMutex);
433 uint32_t len = u_arraylist_length(context->dataList);
435 // #3. add data into list
436 for (i = 0; i < len; i++)
438 CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
440 if (NULL == currData)
446 if (NULL != currData->endpoint && currData->messageId == messageId
447 && (currData->endpoint->adapter == endpoint->adapter))
449 OIC_LOG(ERROR, TAG, "Duplicate message ID");
452 ca_mutex_unlock(context->threadMutex);
456 OICFree(remoteEndpoint);
457 return CA_STATUS_FAILED;
461 u_arraylist_add(context->dataList, (void *) retData);
464 ca_cond_signal(context->threadCond);
467 ca_mutex_unlock(context->threadMutex);
470 u_arraylist_add(context->dataList, (void *) retData);
472 CACheckRetransmissionList(context);
477 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
478 const CAEndpoint_t *endpoint, const void *pdu,
479 uint32_t size, void **retransmissionPdu)
481 OIC_LOG(DEBUG, TAG, "IN");
482 if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
484 OIC_LOG(ERROR, TAG, "invalid parameter");
485 return CA_STATUS_INVALID_PARAM;
488 // #0. check support transport type
489 if (!(context->config.supportType & endpoint->adapter))
491 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
495 // #1. check PDU method type and get message id.
496 // ACK, RST --> remove the CON data
497 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
498 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
499 CAResponseResult_t code = CAGetCodeFromPduBinaryData(pdu, size);
501 OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d, code=%d",
502 type, messageId, code);
504 if (((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
505 || (CA_MSG_RESET == type && CA_EMPTY != code))
511 ca_mutex_lock(context->threadMutex);
512 uint32_t len = u_arraylist_length(context->dataList);
516 for (i = 0; i < len; i++)
518 CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
519 context->dataList, i);
527 if (NULL != retData->endpoint && retData->messageId == messageId
528 && (retData->endpoint->adapter == endpoint->adapter))
530 // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
531 // if retransmission was finish..token will be unavailable.
532 if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
534 OIC_LOG(DEBUG, TAG, "code is CA_EMPTY");
536 if (NULL == retData->pdu)
538 OIC_LOG(ERROR, TAG, "retData->pdu is null");
541 ca_mutex_unlock(context->threadMutex);
543 return CA_STATUS_FAILED;
547 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
548 if ((*retransmissionPdu) == NULL)
551 OIC_LOG(ERROR, TAG, "memory error");
554 ca_mutex_unlock(context->threadMutex);
556 return CA_MEMORY_ALLOC_FAILED;
558 memcpy((*retransmissionPdu), retData->pdu, retData->size);
561 // #2. remove data from list
562 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
563 if (NULL == removedData)
565 OIC_LOG(ERROR, TAG, "Removed data is NULL");
568 ca_mutex_unlock(context->threadMutex);
570 return CA_STATUS_FAILED;
573 OIC_LOG_V(DEBUG, TAG, "remove RTCON data!!, msgid=%d", messageId);
575 CAFreeEndpoint(removedData->endpoint);
576 OICFree(removedData->pdu);
577 OICFree(removedData);
584 ca_mutex_unlock(context->threadMutex);
586 OIC_LOG(DEBUG, TAG, "OUT");
590 CAResult_t CARetransmissionStop(CARetransmission_t *context)
594 OIC_LOG(ERROR, TAG, "context is empty..");
595 return CA_STATUS_INVALID_PARAM;
598 OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
601 ca_mutex_lock(context->threadMutex);
604 context->isStop = true;
607 ca_cond_signal(context->threadCond);
609 ca_cond_wait(context->threadCond, context->threadMutex);
612 ca_mutex_unlock(context->threadMutex);
617 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
621 OIC_LOG(ERROR, TAG, "context is empty..");
622 return CA_STATUS_INVALID_PARAM;
625 OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
627 ca_mutex_free(context->threadMutex);
628 context->threadMutex = NULL;
629 ca_cond_free(context->threadCond);
630 u_arraylist_free(&context->dataList);