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
44 #include "iotivity_config.h"
56 #ifdef HAVE_SYS_TIME_H
59 #ifdef HAVE_SYS_TIMEB_H
60 #include <sys/timeb.h>
67 #if defined(__ANDROID__)
68 #include <linux/time.h>
71 #include "caretransmission.h"
72 #include "caremotehandler.h"
73 #include "caprotocolmessage.h"
74 #include "oic_malloc.h"
79 #define TAG "OIC_CA_RETRANS"
83 uint64_t timeStamp; /**< last sent time. microseconds */
85 uint64_t timeout; /**< timeout value. microseconds */
87 uint8_t triedCount; /**< retransmission count */
88 uint16_t messageId; /**< coap PDU message id */
89 CADataType_t dataType; /**< data Type (Request/Response) */
90 CAEndpoint_t *endpoint; /**< remote endpoint */
91 void *pdu; /**< coap PDU */
92 uint32_t size; /**< coap PDU size */
93 } CARetransmissionData_t;
95 static const uint64_t USECS_PER_SEC = 1000000;
96 static const uint64_t MSECS_PER_SEC = 1000;
100 * @brief timeout value is
101 * between DEFAULT_ACK_TIMEOUT_SEC and
102 * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
103 * DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
104 * @return microseconds.
106 static uint64_t CAGetTimeoutValue()
108 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
112 CAResult_t CARetransmissionStart(CARetransmission_t *context)
116 OIC_LOG(ERROR, TAG, "context is empty");
117 return CA_STATUS_INVALID_PARAM;
120 if (NULL == context->threadPool)
122 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
123 return CA_STATUS_INVALID_PARAM;
126 CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
129 if (CA_STATUS_OK != res)
131 OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
140 * @brief check timeout routine
141 * @param currentTime [IN]microseconds
142 * @param retData [IN]retransmission data
143 * @return true if the timeout period has elapsed, false otherwise
145 static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
147 #ifndef SINGLE_THREAD
148 // #1. calculate timeout
149 uint32_t milliTimeoutValue = retData->timeout * 0.001;
150 uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
152 if (currentTime >= retData->timeStamp + timeout)
154 OIC_LOG_V(DEBUG, TAG, "%" PRIu64 " microseconds time out!!, tried count(%d)",
155 timeout, retData->triedCount);
159 // #1. calculate timeout
160 uint64_t timeOut = (2 << retData->triedCount) * 1000000;
162 if (currentTime >= retData->timeStamp + timeOut)
164 OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
165 (2 << retData->triedCount), retData->triedCount);
172 static void CACheckRetransmissionList(CARetransmission_t *context)
176 OIC_LOG(ERROR, TAG, "context is null");
181 ca_mutex_lock(context->threadMutex);
184 uint32_t len = u_arraylist_length(context->dataList);
186 for (i = 0; i < len; i++)
188 CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
195 uint64_t currentTime = OICGetCurrentTime(TIME_IN_US);
197 if (CACheckTimeout(currentTime, retData))
199 // #2. if time's up, send the data.
200 if (NULL != context->dataSendMethod)
202 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
204 context->dataSendMethod(retData->endpoint, retData->pdu,
205 retData->size, retData->dataType);
208 // #3. increase the retransmission count and update timestamp.
209 retData->timeStamp = currentTime;
210 retData->triedCount++;
213 // #4. if tried count is max, remove the retransmission data from list.
214 if (retData->triedCount >= context->config.tryingCount)
216 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
217 if (NULL == removedData)
219 OIC_LOG(ERROR, TAG, "Removed data is NULL");
221 ca_mutex_unlock(context->threadMutex);
224 OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
225 "msgid=%d", removedData->messageId);
227 // callback for retransmit timeout
228 if (NULL != context->timeoutCallback)
230 context->timeoutCallback(removedData->endpoint, removedData->pdu,
234 CAFreeEndpoint(removedData->endpoint);
235 OICFree(removedData->pdu);
237 OICFree(removedData);
239 // modify loop value.
240 len = u_arraylist_length(context->dataList);
246 ca_mutex_unlock(context->threadMutex);
249 void CARetransmissionBaseRoutine(void *threadValue)
251 OIC_LOG(DEBUG, TAG, "retransmission main thread start");
253 CARetransmission_t *context = (CARetransmission_t *) threadValue;
257 OIC_LOG(ERROR, TAG, "thread data passing error");
263 if (true == context->isStop)
265 OIC_LOG(DEBUG, TAG, "thread stopped");
268 CACheckRetransmissionList(context);
271 while (!context->isStop)
274 ca_mutex_lock(context->threadMutex);
276 if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
278 // if list is empty, thread will wait
279 OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
282 ca_cond_wait(context->threadCond, context->threadMutex);
284 OIC_LOG(DEBUG, TAG, "wake up..");
286 else if (!context->isStop)
288 // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
289 OIC_LOG_V(DEBUG, TAG, "wait..(%" PRIu64 ")microseconds",
290 RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
293 uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
294 ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
298 // we are stopping, so we want to unlock and finish stopping
302 ca_mutex_unlock(context->threadMutex);
310 CACheckRetransmissionList(context);
313 ca_mutex_lock(context->threadMutex);
314 ca_cond_signal(context->threadCond);
315 ca_mutex_unlock(context->threadMutex);
318 OIC_LOG(DEBUG, TAG, "retransmission main thread end");
322 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
323 ca_thread_pool_t handle,
324 CADataSendMethod_t retransmissionSendMethod,
325 CATimeoutCallback_t timeoutCallback,
326 CARetransmissionConfig_t* config)
330 OIC_LOG(ERROR, TAG, "thread instance is empty");
331 return CA_STATUS_INVALID_PARAM;
333 #ifndef SINGLE_THREAD
336 OIC_LOG(ERROR, TAG, "thread pool handle is empty");
337 return CA_STATUS_INVALID_PARAM;
340 OIC_LOG(DEBUG, TAG, "thread initialize");
342 memset(context, 0, sizeof(CARetransmission_t));
344 CARetransmissionConfig_t cfg = { .supportType = DEFAULT_RETRANSMISSION_TYPE,
345 .tryingCount = DEFAULT_RETRANSMISSION_COUNT };
352 // set send thread data
353 context->threadPool = handle;
354 context->threadMutex = ca_mutex_new();
355 context->threadCond = ca_cond_new();
356 context->dataSendMethod = retransmissionSendMethod;
357 context->timeoutCallback = timeoutCallback;
358 context->config = cfg;
359 context->isStop = false;
360 context->dataList = u_arraylist_create();
365 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
366 const CAEndpoint_t *endpoint,
367 CADataType_t dataType,
368 const void *pdu, uint32_t size)
370 if (NULL == context || NULL == endpoint || NULL == pdu)
372 OIC_LOG(ERROR, TAG, "invalid parameter");
373 return CA_STATUS_INVALID_PARAM;
376 // #0. check support transport type
377 if (!(context->config.supportType & endpoint->adapter))
379 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
380 return CA_NOT_SUPPORTED;
383 // #1. check PDU method type and get message id.
384 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
385 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
387 OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d, msgid=%d", type, messageId);
389 if (CA_MSG_CONFIRM != type)
391 OIC_LOG(DEBUG, TAG, "not supported message type");
392 return CA_NOT_SUPPORTED;
395 // create retransmission data
396 CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
397 1, sizeof(CARetransmissionData_t));
401 OIC_LOG(ERROR, TAG, "memory error");
402 return CA_MEMORY_ALLOC_FAILED;
406 void *pduData = (void *) OICMalloc(size);
410 OIC_LOG(ERROR, TAG, "memory error");
411 return CA_MEMORY_ALLOC_FAILED;
413 memcpy(pduData, pdu, size);
415 // clone remote endpoint
416 CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
417 if (NULL == remoteEndpoint)
421 OIC_LOG(ERROR, TAG, "memory error");
422 return CA_MEMORY_ALLOC_FAILED;
425 // #2. add additional information. (time stamp, retransmission count...)
426 retData->timeStamp = OICGetCurrentTime(TIME_IN_US);
427 #ifndef SINGLE_THREAD
428 retData->timeout = CAGetTimeoutValue();
430 retData->triedCount = 0;
431 retData->messageId = messageId;
432 retData->endpoint = remoteEndpoint;
433 retData->pdu = pduData;
434 retData->size = size;
435 retData->dataType = dataType;
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);