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
54 #if defined(__ANDROID__)
55 #include <linux/time.h>
58 #include "caretransmission.h"
59 #include "caremotehandler.h"
60 #include "caprotocolmessage.h"
61 #include "oic_malloc.h"
64 #define TAG "OIC_CA_RETRANS"
68 uint64_t timeStamp; /**< last sent time. microseconds */
70 uint64_t timeout; /**< timeout value. microseconds */
72 uint8_t triedCount; /**< retransmission count */
73 uint16_t messageId; /**< coap PDU message id */
74 CAEndpoint_t *endpoint; /**< remote endpoint */
75 void *pdu; /**< coap PDU */
76 uint32_t size; /**< coap PDU size */
77 } CARetransmissionData_t;
79 static const uint64_t USECS_PER_SEC = 1000000;
82 * @brief getCurrent monotonic time
83 * @return current time in microseconds
85 uint64_t getCurrentTimeInMicroSeconds();
89 * @brief timeout value is
90 * between DEFAULT_ACK_TIMEOUT_SEC and
91 * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
92 * DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
93 * @return microseconds.
95 static uint64_t CAGetTimeoutValue()
97 #if !defined(__msys_nt__)
98 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
101 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (rand() & 0xFF)) >> 8)) *
106 CAResult_t CARetransmissionStart(CARetransmission_t *context)
110 OIC_LOG(ERROR, TAG, "context is empty");
111 return CA_STATUS_INVALID_PARAM;
114 if (NULL == context->threadPool)
116 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
117 return CA_STATUS_INVALID_PARAM;
120 CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
123 if (CA_STATUS_OK != res)
125 OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
134 * @brief check timeout routine
135 * @param currentTime [IN]microseconds
136 * @param retData [IN]retransmission data
137 * @return true if the timeout period has elapsed, false otherwise
139 static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
141 #ifndef SINGLE_THREAD
142 // #1. calculate timeout
143 uint32_t milliTimeoutValue = retData->timeout * 0.001;
144 uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
146 if (currentTime >= retData->timeStamp + timeout)
148 OIC_LOG_V(DEBUG, TAG, "%llu microseconds time out!!, tried count(%d)",
149 timeout, retData->triedCount);
153 // #1. calculate timeout
154 uint64_t timeOut = (2 << retData->triedCount) * 1000000;
156 if (currentTime >= retData->timeStamp + timeOut)
158 OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
159 (2 << retData->triedCount), retData->triedCount);
166 static void CACheckRetransmissionList(CARetransmission_t *context)
170 OIC_LOG(ERROR, TAG, "context is null");
175 ca_mutex_lock(context->threadMutex);
178 uint32_t len = u_arraylist_length(context->dataList);
180 for (i = 0; i < len; i++)
182 CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
189 uint64_t currentTime = getCurrentTimeInMicroSeconds();
191 if (CACheckTimeout(currentTime, retData))
193 // #2. if time's up, send the data.
194 if (NULL != context->dataSendMethod)
196 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
198 context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
201 // #3. increase the retransmission count and update timestamp.
202 retData->timeStamp = currentTime;
203 retData->triedCount++;
206 // #4. if tried count is max, remove the retransmission data from list.
207 if (retData->triedCount >= context->config.tryingCount)
209 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
210 if (NULL == removedData)
212 OIC_LOG(ERROR, TAG, "Removed data is NULL");
214 ca_mutex_unlock(context->threadMutex);
217 OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
218 "msgid=%d", removedData->messageId);
220 // callback for retransmit timeout
221 if (NULL != context->timeoutCallback)
223 context->timeoutCallback(removedData->endpoint, removedData->pdu,
227 CAFreeEndpoint(removedData->endpoint);
228 OICFree(removedData->pdu);
230 OICFree(removedData);
232 // modify loop value.
233 len = u_arraylist_length(context->dataList);
239 ca_mutex_unlock(context->threadMutex);
242 void CARetransmissionBaseRoutine(void *threadValue)
244 OIC_LOG(DEBUG, TAG, "retransmission main thread start");
246 CARetransmission_t *context = (CARetransmission_t *) threadValue;
250 OIC_LOG(ERROR, TAG, "thread data passing error");
256 if (true == context->isStop)
258 OIC_LOG(DEBUG, TAG, "thread stopped");
261 CACheckRetransmissionList(context);
264 while (!context->isStop)
267 ca_mutex_lock(context->threadMutex);
269 if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
271 // if list is empty, thread will wait
272 OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
275 ca_cond_wait(context->threadCond, context->threadMutex);
277 OIC_LOG(DEBUG, TAG, "wake up..");
279 else if (!context->isStop)
281 // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
282 OIC_LOG_V(DEBUG, TAG, "wait..(%lld)microseconds",
283 RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
286 uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
287 ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
291 // we are stopping, so we want to unlock and finish stopping
295 ca_mutex_unlock(context->threadMutex);
303 CACheckRetransmissionList(context);
306 ca_mutex_lock(context->threadMutex);
307 ca_cond_signal(context->threadCond);
308 ca_mutex_unlock(context->threadMutex);
311 OIC_LOG(DEBUG, TAG, "retransmission main thread end");
315 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
316 ca_thread_pool_t handle,
317 CADataSendMethod_t retransmissionSendMethod,
318 CATimeoutCallback_t timeoutCallback,
319 CARetransmissionConfig_t* config)
323 OIC_LOG(ERROR, TAG, "thread instance is empty");
324 return CA_STATUS_INVALID_PARAM;
326 #ifndef SINGLE_THREAD
329 OIC_LOG(ERROR, TAG, "thread pool handle is empty");
330 return CA_STATUS_INVALID_PARAM;
333 OIC_LOG(DEBUG, TAG, "thread initialize");
335 memset(context, 0, sizeof(CARetransmission_t));
337 CARetransmissionConfig_t cfg = { .supportType = DEFAULT_RETRANSMISSION_TYPE,
338 .tryingCount = DEFAULT_RETRANSMISSION_COUNT };
345 // set send thread data
346 context->threadPool = handle;
347 context->threadMutex = ca_mutex_new();
348 context->threadCond = ca_cond_new();
349 context->dataSendMethod = retransmissionSendMethod;
350 context->timeoutCallback = timeoutCallback;
351 context->config = cfg;
352 context->isStop = false;
353 context->dataList = u_arraylist_create();
358 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
359 const CAEndpoint_t *endpoint,
360 const void *pdu, uint32_t size)
362 if (NULL == context || NULL == endpoint || NULL == pdu)
364 OIC_LOG(ERROR, TAG, "invalid parameter");
365 return CA_STATUS_INVALID_PARAM;
368 // #0. check support transport type
369 if (!(context->config.supportType & endpoint->adapter))
371 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
372 return CA_NOT_SUPPORTED;
375 // #1. check PDU method type and get message id.
376 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
377 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
379 OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d, msgid=%d", type, messageId);
381 if (CA_MSG_CONFIRM != type)
383 OIC_LOG(DEBUG, TAG, "not supported message type");
384 return CA_NOT_SUPPORTED;
387 // create retransmission data
388 CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
389 1, sizeof(CARetransmissionData_t));
393 OIC_LOG(ERROR, TAG, "memory error");
394 return CA_MEMORY_ALLOC_FAILED;
398 void *pduData = (void *) OICMalloc(size);
402 OIC_LOG(ERROR, TAG, "memory error");
403 return CA_MEMORY_ALLOC_FAILED;
405 memcpy(pduData, pdu, size);
407 // clone remote endpoint
408 CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
409 if (NULL == remoteEndpoint)
413 OIC_LOG(ERROR, TAG, "memory error");
414 return CA_MEMORY_ALLOC_FAILED;
417 // #2. add additional information. (time stamp, retransmission count...)
418 retData->timeStamp = getCurrentTimeInMicroSeconds();
419 #ifndef SINGLE_THREAD
420 retData->timeout = CAGetTimeoutValue();
422 retData->triedCount = 0;
423 retData->messageId = messageId;
424 retData->endpoint = remoteEndpoint;
425 retData->pdu = pduData;
426 retData->size = size;
427 #ifndef SINGLE_THREAD
429 ca_mutex_lock(context->threadMutex);
432 uint32_t len = u_arraylist_length(context->dataList);
434 // #3. add data into list
435 for (i = 0; i < len; i++)
437 CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
439 if (NULL == currData)
445 if (NULL != currData->endpoint && currData->messageId == messageId
446 && (currData->endpoint->adapter == endpoint->adapter))
448 OIC_LOG(ERROR, TAG, "Duplicate message ID");
451 ca_mutex_unlock(context->threadMutex);
455 OICFree(remoteEndpoint);
456 return CA_STATUS_FAILED;
460 u_arraylist_add(context->dataList, (void *) retData);
463 ca_cond_signal(context->threadCond);
466 ca_mutex_unlock(context->threadMutex);
469 u_arraylist_add(context->dataList, (void *) retData);
471 CACheckRetransmissionList(context);
476 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
477 const CAEndpoint_t *endpoint, const void *pdu,
478 uint32_t size, void **retransmissionPdu)
480 OIC_LOG(DEBUG, TAG, "IN");
481 if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
483 OIC_LOG(ERROR, TAG, "invalid parameter");
484 return CA_STATUS_INVALID_PARAM;
487 // #0. check support transport type
488 if (!(context->config.supportType & endpoint->adapter))
490 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
494 // #1. check PDU method type and get message id.
495 // ACK, RST --> remove the CON data
496 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
497 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
498 CAResponseResult_t code = CAGetCodeFromPduBinaryData(pdu, size);
500 OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d, code=%d",
501 type, messageId, code);
503 if (((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
504 || (CA_MSG_RESET == type && CA_EMPTY != code))
510 ca_mutex_lock(context->threadMutex);
511 uint32_t len = u_arraylist_length(context->dataList);
515 for (i = 0; i < len; i++)
517 CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
518 context->dataList, i);
526 if (NULL != retData->endpoint && retData->messageId == messageId
527 && (retData->endpoint->adapter == endpoint->adapter))
529 // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
530 // if retransmission was finish..token will be unavailable.
531 if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
533 OIC_LOG(DEBUG, TAG, "code is CA_EMPTY");
535 if (NULL == retData->pdu)
537 OIC_LOG(ERROR, TAG, "retData->pdu is null");
540 ca_mutex_unlock(context->threadMutex);
542 return CA_STATUS_FAILED;
546 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
547 if ((*retransmissionPdu) == NULL)
550 OIC_LOG(ERROR, TAG, "memory error");
553 ca_mutex_unlock(context->threadMutex);
555 return CA_MEMORY_ALLOC_FAILED;
557 memcpy((*retransmissionPdu), retData->pdu, retData->size);
560 // #2. remove data from list
561 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
562 if (NULL == removedData)
564 OIC_LOG(ERROR, TAG, "Removed data is NULL");
567 ca_mutex_unlock(context->threadMutex);
569 return CA_STATUS_FAILED;
572 OIC_LOG_V(DEBUG, TAG, "remove RTCON data!!, msgid=%d", messageId);
574 CAFreeEndpoint(removedData->endpoint);
575 OICFree(removedData->pdu);
576 OICFree(removedData);
583 ca_mutex_unlock(context->threadMutex);
585 OIC_LOG(DEBUG, TAG, "OUT");
589 CAResult_t CARetransmissionStop(CARetransmission_t *context)
593 OIC_LOG(ERROR, TAG, "context is empty..");
594 return CA_STATUS_INVALID_PARAM;
597 OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
600 ca_mutex_lock(context->threadMutex);
603 context->isStop = true;
606 ca_cond_signal(context->threadCond);
608 ca_cond_wait(context->threadCond, context->threadMutex);
611 ca_mutex_unlock(context->threadMutex);
616 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
620 OIC_LOG(ERROR, TAG, "context is empty..");
621 return CA_STATUS_INVALID_PARAM;
624 OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
626 ca_mutex_free(context->threadMutex);
627 context->threadMutex = NULL;
628 ca_cond_free(context->threadCond);
629 u_arraylist_free(&context->dataList);
634 uint64_t getCurrentTimeInMicroSeconds()
636 OIC_LOG(DEBUG, TAG, "IN");
637 uint64_t currentTime = 0;
640 struct timespec getTs;
642 clock_gettime(CLOCK_MONOTONIC, &getTs);
644 currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
645 OIC_LOG_V(DEBUG, TAG, "current time = %lld", currentTime);
646 #elif defined __ARDUINO__
647 currentTime = millis() * 1000;
648 OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
650 #if _POSIX_TIMERS > 0
652 clock_gettime(CLOCK_MONOTONIC, &ts);
653 currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
656 gettimeofday(&tv, NULL);
657 currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
661 OIC_LOG(DEBUG, TAG, "OUT");