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"
73 #define TAG "OIC_CA_RETRANS"
77 uint64_t timeStamp; /**< last sent time. microseconds */
79 uint64_t timeout; /**< timeout value. microseconds */
81 uint8_t triedCount; /**< retransmission count */
82 uint16_t messageId; /**< coap PDU message id */
83 CAEndpoint_t *endpoint; /**< remote endpoint */
84 void *pdu; /**< coap PDU */
85 uint32_t size; /**< coap PDU size */
86 } CARetransmissionData_t;
88 static const uint64_t USECS_PER_SEC = 1000000;
91 * @brief getCurrent monotonic time
92 * @return current time in microseconds
94 uint64_t getCurrentTimeInMicroSeconds();
98 * @brief timeout value is
99 * between DEFAULT_ACK_TIMEOUT_SEC and
100 * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
101 * DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
102 * @return microseconds.
104 static uint64_t CAGetTimeoutValue()
106 #if !defined(__msys_nt__)
107 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
110 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (rand() & 0xFF)) >> 8)) *
115 CAResult_t CARetransmissionStart(CARetransmission_t *context)
119 OIC_LOG(ERROR, TAG, "context is empty");
120 return CA_STATUS_INVALID_PARAM;
123 if (NULL == context->threadPool)
125 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
126 return CA_STATUS_INVALID_PARAM;
129 CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
132 if (CA_STATUS_OK != res)
134 OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
143 * @brief check timeout routine
144 * @param currentTime [IN]microseconds
145 * @param retData [IN]retransmission data
146 * @return true if the timeout period has elapsed, false otherwise
148 static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
150 #ifndef SINGLE_THREAD
151 // #1. calculate timeout
152 uint32_t milliTimeoutValue = retData->timeout * 0.001;
153 uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
155 if (currentTime >= retData->timeStamp + timeout)
157 OIC_LOG_V(DEBUG, TAG, "%llu microseconds time out!!, tried count(%d)",
158 timeout, retData->triedCount);
162 // #1. calculate timeout
163 uint64_t timeOut = (2 << retData->triedCount) * 1000000;
165 if (currentTime >= retData->timeStamp + timeOut)
167 OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
168 (2 << retData->triedCount), retData->triedCount);
175 static void CACheckRetransmissionList(CARetransmission_t *context)
179 OIC_LOG(ERROR, TAG, "context is null");
184 ca_mutex_lock(context->threadMutex);
187 uint32_t len = u_arraylist_length(context->dataList);
189 for (i = 0; i < len; i++)
191 CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
198 uint64_t currentTime = getCurrentTimeInMicroSeconds();
200 if (CACheckTimeout(currentTime, retData))
202 // #2. if time's up, send the data.
203 if (NULL != context->dataSendMethod)
205 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
207 context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
210 // #3. increase the retransmission count and update timestamp.
211 retData->timeStamp = currentTime;
212 retData->triedCount++;
215 // #4. if tried count is max, remove the retransmission data from list.
216 if (retData->triedCount >= context->config.tryingCount)
218 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
219 if (NULL == removedData)
221 OIC_LOG(ERROR, TAG, "Removed data is NULL");
223 ca_mutex_unlock(context->threadMutex);
226 OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
227 "msgid=%d", removedData->messageId);
229 // callback for retransmit timeout
230 if (NULL != context->timeoutCallback)
232 context->timeoutCallback(removedData->endpoint, removedData->pdu,
236 CAFreeEndpoint(removedData->endpoint);
237 OICFree(removedData->pdu);
239 OICFree(removedData);
241 // modify loop value.
242 len = u_arraylist_length(context->dataList);
248 ca_mutex_unlock(context->threadMutex);
251 void CARetransmissionBaseRoutine(void *threadValue)
253 OIC_LOG(DEBUG, TAG, "retransmission main thread start");
255 CARetransmission_t *context = (CARetransmission_t *) threadValue;
259 OIC_LOG(ERROR, TAG, "thread data passing error");
265 if (true == context->isStop)
267 OIC_LOG(DEBUG, TAG, "thread stopped");
270 CACheckRetransmissionList(context);
273 while (!context->isStop)
276 ca_mutex_lock(context->threadMutex);
278 if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
280 // if list is empty, thread will wait
281 OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
284 ca_cond_wait(context->threadCond, context->threadMutex);
286 OIC_LOG(DEBUG, TAG, "wake up..");
288 else if (!context->isStop)
290 // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
291 OIC_LOG_V(DEBUG, TAG, "wait..(%lld)microseconds",
292 RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
295 uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
296 ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
300 // we are stopping, so we want to unlock and finish stopping
304 ca_mutex_unlock(context->threadMutex);
312 CACheckRetransmissionList(context);
315 ca_mutex_lock(context->threadMutex);
316 ca_cond_signal(context->threadCond);
317 ca_mutex_unlock(context->threadMutex);
320 OIC_LOG(DEBUG, TAG, "retransmission main thread end");
324 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
325 ca_thread_pool_t handle,
326 CADataSendMethod_t retransmissionSendMethod,
327 CATimeoutCallback_t timeoutCallback,
328 CARetransmissionConfig_t* config)
332 OIC_LOG(ERROR, TAG, "thread instance is empty");
333 return CA_STATUS_INVALID_PARAM;
335 #ifndef SINGLE_THREAD
338 OIC_LOG(ERROR, TAG, "thread pool handle is empty");
339 return CA_STATUS_INVALID_PARAM;
342 OIC_LOG(DEBUG, TAG, "thread initialize");
344 memset(context, 0, sizeof(CARetransmission_t));
346 CARetransmissionConfig_t cfg = { .supportType = DEFAULT_RETRANSMISSION_TYPE,
347 .tryingCount = DEFAULT_RETRANSMISSION_COUNT };
354 // set send thread data
355 context->threadPool = handle;
356 context->threadMutex = ca_mutex_new();
357 context->threadCond = ca_cond_new();
358 context->dataSendMethod = retransmissionSendMethod;
359 context->timeoutCallback = timeoutCallback;
360 context->config = cfg;
361 context->isStop = false;
362 context->dataList = u_arraylist_create();
367 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
368 const CAEndpoint_t *endpoint,
369 const void *pdu, uint32_t size)
371 if (NULL == context || NULL == endpoint || NULL == pdu)
373 OIC_LOG(ERROR, TAG, "invalid parameter");
374 return CA_STATUS_INVALID_PARAM;
377 // #0. check support transport type
378 if (!(context->config.supportType & endpoint->adapter))
380 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
381 return CA_NOT_SUPPORTED;
384 // #1. check PDU method type and get message id.
385 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
386 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
388 OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d, msgid=%d", type, messageId);
390 if (CA_MSG_CONFIRM != type)
392 OIC_LOG(DEBUG, TAG, "not supported message type");
393 return CA_NOT_SUPPORTED;
396 // create retransmission data
397 CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
398 1, sizeof(CARetransmissionData_t));
402 OIC_LOG(ERROR, TAG, "memory error");
403 return CA_MEMORY_ALLOC_FAILED;
407 void *pduData = (void *) OICMalloc(size);
411 OIC_LOG(ERROR, TAG, "memory error");
412 return CA_MEMORY_ALLOC_FAILED;
414 memcpy(pduData, pdu, size);
416 // clone remote endpoint
417 CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
418 if (NULL == remoteEndpoint)
422 OIC_LOG(ERROR, TAG, "memory error");
423 return CA_MEMORY_ALLOC_FAILED;
426 // #2. add additional information. (time stamp, retransmission count...)
427 retData->timeStamp = getCurrentTimeInMicroSeconds();
428 #ifndef SINGLE_THREAD
429 retData->timeout = CAGetTimeoutValue();
431 retData->triedCount = 0;
432 retData->messageId = messageId;
433 retData->endpoint = remoteEndpoint;
434 retData->pdu = pduData;
435 retData->size = size;
436 #ifndef SINGLE_THREAD
438 ca_mutex_lock(context->threadMutex);
441 uint32_t len = u_arraylist_length(context->dataList);
443 // #3. add data into list
444 for (i = 0; i < len; i++)
446 CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
448 if (NULL == currData)
454 if (NULL != currData->endpoint && currData->messageId == messageId
455 && (currData->endpoint->adapter == endpoint->adapter))
457 OIC_LOG(ERROR, TAG, "Duplicate message ID");
460 ca_mutex_unlock(context->threadMutex);
464 OICFree(remoteEndpoint);
465 return CA_STATUS_FAILED;
469 u_arraylist_add(context->dataList, (void *) retData);
472 ca_cond_signal(context->threadCond);
475 ca_mutex_unlock(context->threadMutex);
478 u_arraylist_add(context->dataList, (void *) retData);
480 CACheckRetransmissionList(context);
485 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
486 const CAEndpoint_t *endpoint, const void *pdu,
487 uint32_t size, void **retransmissionPdu)
489 OIC_LOG(DEBUG, TAG, "IN");
490 if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
492 OIC_LOG(ERROR, TAG, "invalid parameter");
493 return CA_STATUS_INVALID_PARAM;
496 // #0. check support transport type
497 if (!(context->config.supportType & endpoint->adapter))
499 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
503 // #1. check PDU method type and get message id.
504 // ACK, RST --> remove the CON data
505 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
506 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
507 CAResponseResult_t code = CAGetCodeFromPduBinaryData(pdu, size);
509 OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d, code=%d",
510 type, messageId, code);
512 if (((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
513 || (CA_MSG_RESET == type && CA_EMPTY != code))
519 ca_mutex_lock(context->threadMutex);
520 uint32_t len = u_arraylist_length(context->dataList);
524 for (i = 0; i < len; i++)
526 CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
527 context->dataList, i);
535 if (NULL != retData->endpoint && retData->messageId == messageId
536 && (retData->endpoint->adapter == endpoint->adapter))
538 // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
539 // if retransmission was finish..token will be unavailable.
540 if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
542 OIC_LOG(DEBUG, TAG, "code is CA_EMPTY");
544 if (NULL == retData->pdu)
546 OIC_LOG(ERROR, TAG, "retData->pdu is null");
549 ca_mutex_unlock(context->threadMutex);
551 return CA_STATUS_FAILED;
555 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
556 if ((*retransmissionPdu) == NULL)
559 OIC_LOG(ERROR, TAG, "memory error");
562 ca_mutex_unlock(context->threadMutex);
564 return CA_MEMORY_ALLOC_FAILED;
566 memcpy((*retransmissionPdu), retData->pdu, retData->size);
569 // #2. remove data from list
570 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
571 if (NULL == removedData)
573 OIC_LOG(ERROR, TAG, "Removed data is NULL");
576 ca_mutex_unlock(context->threadMutex);
578 return CA_STATUS_FAILED;
581 OIC_LOG_V(DEBUG, TAG, "remove RTCON data!!, msgid=%d", messageId);
583 CAFreeEndpoint(removedData->endpoint);
584 OICFree(removedData->pdu);
585 OICFree(removedData);
592 ca_mutex_unlock(context->threadMutex);
594 OIC_LOG(DEBUG, TAG, "OUT");
598 CAResult_t CARetransmissionStop(CARetransmission_t *context)
602 OIC_LOG(ERROR, TAG, "context is empty..");
603 return CA_STATUS_INVALID_PARAM;
606 OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
609 ca_mutex_lock(context->threadMutex);
612 context->isStop = true;
615 ca_cond_signal(context->threadCond);
617 ca_cond_wait(context->threadCond, context->threadMutex);
620 ca_mutex_unlock(context->threadMutex);
625 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
629 OIC_LOG(ERROR, TAG, "context is empty..");
630 return CA_STATUS_INVALID_PARAM;
633 OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
635 ca_mutex_free(context->threadMutex);
636 context->threadMutex = NULL;
637 ca_cond_free(context->threadCond);
638 u_arraylist_free(&context->dataList);
643 uint64_t getCurrentTimeInMicroSeconds()
645 OIC_LOG(DEBUG, TAG, "IN");
646 uint64_t currentTime = 0;
649 struct timespec getTs;
651 clock_gettime(CLOCK_MONOTONIC, &getTs);
653 currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
654 OIC_LOG_V(DEBUG, TAG, "current time = %lld", currentTime);
655 #elif defined __ARDUINO__
656 currentTime = millis() * 1000;
657 OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
659 #if _POSIX_TIMERS > 0
661 clock_gettime(CLOCK_MONOTONIC, &ts);
662 currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
665 gettimeofday(&tv, NULL);
666 currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
670 OIC_LOG(DEBUG, TAG, "OUT");