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
33 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
34 // causes header files to expose definitions
35 // corresponding to the POSIX.1b, Real-time extensions
36 // (IEEE Std 1003.1b-1993) specification
38 // For this specific file, see use of clock_gettime,
39 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
40 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
41 #ifndef _POSIX_C_SOURCE
42 #define _POSIX_C_SOURCE 200809L
52 #if defined(__ANDROID__)
53 #include <linux/time.h>
56 #include "caretransmission.h"
57 #include "caremotehandler.h"
58 #include "caprotocolmessage.h"
59 #include "oic_malloc.h"
66 uint64_t timeStamp; /**< last sent time. microseconds */
67 uint64_t timeout; /**< timeout value. microseconds */
68 uint8_t triedCount; /**< retransmission count */
69 uint16_t messageId; /**< coap PDU message id */
70 CARemoteEndpoint_t *endpoint; /**< remote endpoint */
71 void *pdu; /**< coap PDU */
72 uint32_t size; /**< coap PDU size */
73 } CARetransmissionData_t;
75 static const uint64_t USECS_PER_SEC = 1000000;
78 * @brief getCurrent monotonic time
79 * @return current time in microseconds
81 uint64_t getCurrentTimeInMicroSeconds();
84 * @brief check timeout routine
85 * @param currentTime [IN]microseconds
86 * @param timeStamp [IN]microseconds
87 * @param timeoutValue [IN]microseconds
88 * @param triedCount [IN]Number of retransmission tried
89 * @return true if the timeout period has elapsed, false otherwise
91 static bool CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint64_t timeoutValue,
94 // #1. calculate timeout
95 uint32_t milliTimeoutValue = timeoutValue * 0.001;
96 uint64_t timeout = (milliTimeoutValue << triedCount) * (uint64_t) 1000;
98 if (currentTime >= timeStamp + timeout)
100 OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%d)", timeout, triedCount);
108 * @brief timeout value is
109 * between DEFAULT_ACK_TIMEOUT_SEC and
110 * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
111 * DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
112 * @return microseconds.
114 static uint64_t CAGetTimeoutValue()
116 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
120 static void CACheckRetransmissionList(CARetransmission_t *context)
124 OIC_LOG(ERROR, TAG, "context is null..");
129 ca_mutex_lock(context->threadMutex);
132 uint32_t len = u_arraylist_length(context->dataList);
134 for (i = 0; i < len; i++)
136 CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
143 uint64_t currentTime = getCurrentTimeInMicroSeconds();
145 if (CACheckTimeout(currentTime, retData->timeStamp, retData->timeout, retData->triedCount))
147 // #2. if time's up, send the data.
148 if (NULL != context->dataSendMethod)
150 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, message id(%d)",
152 context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
155 // #3. increase the retransmission count and update timestamp.
156 retData->timeStamp = currentTime;
157 retData->triedCount++;
160 // #4. if tried count is max, remove the retransmission data from list.
161 if (retData->triedCount >= context->config.tryingCount)
163 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
165 if (NULL != removedData)
167 OIC_LOG_V(DEBUG, TAG, "max trying count, remove retransmission CON data!!,\
168 message id(%d)", removedData->messageId);
170 // callback for retransmit timeout
171 if (NULL != context->timeoutCallback)
173 context->timeoutCallback(removedData->endpoint, removedData->pdu,
177 CADestroyRemoteEndpointInternal(removedData->endpoint);
178 OICFree(removedData->pdu);
180 OICFree(removedData);
182 // modify loop value.
183 len = u_arraylist_length(context->dataList);
189 OIC_LOG(ERROR, TAG, "arraylist remove error");
196 ca_mutex_unlock(context->threadMutex);
199 static void CARetransmissionBaseRoutine(void *threadValue)
201 OIC_LOG(DEBUG, TAG, "retransmission main thread start..");
203 CARetransmission_t *context = (CARetransmission_t *) threadValue;
207 OIC_LOG(ERROR, TAG, "thread data passing error!!");
212 while (!context->isStop)
215 ca_mutex_lock(context->threadMutex);
217 if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
219 // if list is empty, thread will wait
220 OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
223 ca_cond_wait(context->threadCond, context->threadMutex);
225 OIC_LOG(DEBUG, TAG, "wake up..");
229 // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
230 OIC_LOG_V(DEBUG, TAG, "wait..(%d)microseconds",
231 RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
234 uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
235 ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
239 ca_mutex_unlock(context->threadMutex);
247 CACheckRetransmissionList(context);
250 ca_mutex_lock(context->threadMutex);
251 ca_cond_signal(context->threadCond);
252 ca_mutex_unlock(context->threadMutex);
254 OIC_LOG(DEBUG, TAG, "retransmission main thread end..");
258 CAResult_t CARetransmissionInitialize(CARetransmission_t *context, ca_thread_pool_t handle,
259 CADataSendMethod_t retransmissionSendMethod,
260 CATimeoutCallback_t timeoutCallback,
261 CARetransmissionConfig_t* config)
265 OIC_LOG(ERROR, TAG, "thread instance is empty..");
266 return CA_STATUS_INVALID_PARAM;
271 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
272 return CA_STATUS_INVALID_PARAM;
275 OIC_LOG(DEBUG, TAG, "thread initialize..");
277 memset(context, 0, sizeof(CARetransmission_t));
279 CARetransmissionConfig_t cfg = { 0 };
284 cfg.supportType = DEFAULT_RETRANSMISSION_TYPE;
285 cfg.tryingCount = DEFAULT_MAX_RETRANSMIT;
292 // set send thread data
293 context->threadPool = handle;
294 context->threadMutex = ca_mutex_new();
295 context->threadCond = ca_cond_new();
296 context->dataSendMethod = retransmissionSendMethod;
297 context->timeoutCallback = timeoutCallback;
298 context->config = cfg;
299 context->isStop = false;
300 context->dataList = u_arraylist_create();
305 CAResult_t CARetransmissionStart(CARetransmission_t *context)
309 OIC_LOG(ERROR, TAG, "context is empty..");
310 return CA_STATUS_INVALID_PARAM;
313 if (NULL == context->threadPool)
315 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
316 return CA_STATUS_INVALID_PARAM;
319 CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
322 if (CA_STATUS_OK != res)
324 OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
331 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
332 const CARemoteEndpoint_t* endpoint, const void* pdu,
335 if (NULL == context || NULL == endpoint || NULL == pdu)
337 OIC_LOG(ERROR, TAG, "invalid parameter..");
338 return CA_STATUS_INVALID_PARAM;
341 // #0. check support connectivity type
342 if (!(context->config.supportType & endpoint->connectivityType))
344 OIC_LOG_V(DEBUG, TAG, "not supported connectivity type for retransmission..(%d)",
345 endpoint->connectivityType);
346 return CA_NOT_SUPPORTED;
349 // #1. check PDU method type and get message id.
350 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
351 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
353 OIC_LOG_V(DEBUG, TAG, "sent pdu, message type(%d), message id(%d)", type, messageId);
355 if (CA_MSG_CONFIRM != type)
357 OIC_LOG(DEBUG, TAG, "not supported message type for retransmission..");
358 return CA_NOT_SUPPORTED;
361 // create retransmission data
362 CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
363 1, sizeof(CARetransmissionData_t));
367 OIC_LOG(ERROR, TAG, "memory error!!");
368 return CA_MEMORY_ALLOC_FAILED;
372 void *pduData = (void *) OICMalloc(size);
376 OIC_LOG(ERROR, TAG, "memory error!!");
377 return CA_MEMORY_ALLOC_FAILED;
379 memcpy(pduData, pdu, size);
381 // clone remote endpoint
382 CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(endpoint);
383 if (NULL == remoteEndpoint)
387 OIC_LOG(ERROR, TAG, "memory error!!");
388 return CA_MEMORY_ALLOC_FAILED;
391 // #2. add additional information. (time stamp, retransmission count...)
392 retData->timeStamp = getCurrentTimeInMicroSeconds();
393 retData->timeout = CAGetTimeoutValue();
394 retData->triedCount = 0;
395 retData->messageId = messageId;
396 retData->endpoint = remoteEndpoint;
397 retData->pdu = pduData;
398 retData->size = size;
401 ca_mutex_lock(context->threadMutex);
404 uint32_t len = u_arraylist_length(context->dataList);
406 // #3. add data into list
407 for (i = 0; i < len; i++)
409 CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
411 if (NULL == currData)
417 if (NULL != currData->endpoint && currData->messageId == messageId
418 && (currData->endpoint->connectivityType == endpoint->connectivityType))
420 OIC_LOG(ERROR, TAG, "Duplicate message ID");
423 ca_mutex_unlock(context->threadMutex);
427 OICFree(remoteEndpoint);
428 return CA_STATUS_FAILED;
432 u_arraylist_add(context->dataList, (void *) retData);
435 ca_cond_signal(context->threadCond);
438 ca_mutex_unlock(context->threadMutex);
443 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
444 const CARemoteEndpoint_t *endpoint, const void *pdu,
445 uint32_t size, void **retransmissionPdu)
447 OIC_LOG(DEBUG, TAG, "IN - CARetransmissionReceivedData");
448 if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
450 OIC_LOG(ERROR, TAG, "invalid parameter..");
451 return CA_STATUS_INVALID_PARAM;
454 // #0. check support connectivity type
455 if (!(context->config.supportType & endpoint->connectivityType))
457 OIC_LOG_V(DEBUG, TAG, "not supported connectivity type for retransmission..(%d)",
458 endpoint->connectivityType);
462 // #1. check PDU method type and get message id.
463 // ACK, RST --> remove the CON data
464 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
465 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
467 OIC_LOG_V(DEBUG, TAG, "received pdu, message type(%d), message id(%d)", type, messageId);
469 if ((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
475 ca_mutex_lock(context->threadMutex);
476 uint32_t len = u_arraylist_length(context->dataList);
479 for (uint32_t i = 0; i < len; i++)
481 CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
482 context->dataList, i);
490 if (NULL != retData->endpoint && retData->messageId == messageId
491 && (retData->endpoint->connectivityType == endpoint->connectivityType))
493 // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
494 // if retransmission was finish..token will be unavailable.
495 if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
497 OIC_LOG(DEBUG, TAG, "code is CA_EMPTY..");
499 if (NULL == retData->pdu)
501 OIC_LOG(ERROR, TAG, "retData->pdu is null");
504 ca_mutex_unlock(context->threadMutex);
506 return CA_STATUS_FAILED;
510 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
511 if ((*retransmissionPdu) == NULL)
514 OIC_LOG(ERROR, TAG, "memory error!!");
517 ca_mutex_unlock(context->threadMutex);
519 return CA_MEMORY_ALLOC_FAILED;
521 memcpy((*retransmissionPdu), retData->pdu, retData->size);
524 // #2. remove data from list
525 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
526 if (NULL == removedData)
528 OIC_LOG(ERROR, TAG, "Removed data is NULL");
531 ca_mutex_unlock(context->threadMutex);
533 return CA_STATUS_FAILED;
536 OIC_LOG_V(DEBUG, TAG, "remove retransmission CON data!!, message id(%d)",
539 CADestroyRemoteEndpointInternal(removedData->endpoint);
540 OICFree(removedData->pdu);
541 OICFree(removedData);
548 ca_mutex_unlock(context->threadMutex);
550 OIC_LOG(DEBUG, TAG, "OUT - CARetransmissionReceivedData");
554 CAResult_t CARetransmissionStop(CARetransmission_t *context)
558 OIC_LOG(ERROR, TAG, "context is empty..");
559 return CA_STATUS_INVALID_PARAM;
562 OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
565 ca_mutex_lock(context->threadMutex);
568 context->isStop = true;
571 ca_cond_signal(context->threadCond);
573 ca_cond_wait(context->threadCond, context->threadMutex);
576 ca_mutex_unlock(context->threadMutex);
581 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
585 OIC_LOG(ERROR, TAG, "context is empty..");
586 return CA_STATUS_INVALID_PARAM;
589 OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
591 ca_mutex_free(context->threadMutex);
592 context->threadMutex = NULL;
593 ca_cond_free(context->threadCond);
594 u_arraylist_free(&context->dataList);
599 uint64_t getCurrentTimeInMicroSeconds()
601 OIC_LOG(DEBUG, TAG, "IN");
602 uint64_t currentTime = 0;
605 struct timespec getTs;
607 clock_gettime(CLOCK_MONOTONIC, &getTs);
609 currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
610 OIC_LOG_V(DEBUG, TAG, "current time = %d", currentTime);
612 #if _POSIX_TIMERS > 0
614 clock_gettime(CLOCK_MONOTONIC, &ts);
615 currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
618 gettimeofday(&tv, NULL);
619 currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
623 OIC_LOG(DEBUG, TAG, "OUT");