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 CADataType_t dataType; /**< data Type (Request/Response) */
86 CAEndpoint_t *endpoint; /**< remote endpoint */
87 void *pdu; /**< coap PDU */
88 uint32_t size; /**< coap PDU size */
89 } CARetransmissionData_t;
91 static const uint64_t USECS_PER_SEC = 1000000;
92 static const uint64_t MSECS_PER_SEC = 1000;
96 * @brief timeout value is
97 * between DEFAULT_ACK_TIMEOUT_SEC and
98 * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
99 * DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
100 * @return microseconds.
102 static uint64_t CAGetTimeoutValue()
104 return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * OCGetRandomByte()) >> 8)) *
108 CAResult_t CARetransmissionStart(CARetransmission_t *context)
112 OIC_LOG(ERROR, TAG, "context is empty");
113 return CA_STATUS_INVALID_PARAM;
116 if (NULL == context->threadPool)
118 OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
119 return CA_STATUS_INVALID_PARAM;
122 CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
125 if (CA_STATUS_OK != res)
127 OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
136 * @brief check timeout routine
137 * @param currentTime [IN]microseconds
138 * @param retData [IN]retransmission data
139 * @return true if the timeout period has elapsed, false otherwise
141 static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
143 #ifndef SINGLE_THREAD
144 // #1. calculate timeout
145 uint32_t milliTimeoutValue = retData->timeout * 0.001;
146 uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
148 if (currentTime >= retData->timeStamp + timeout)
150 OIC_LOG_V(DEBUG, TAG, "%llu microseconds time out!!, tried count(%d)",
151 timeout, retData->triedCount);
155 // #1. calculate timeout
156 uint64_t timeOut = (2 << retData->triedCount) * 1000000;
158 if (currentTime >= retData->timeStamp + timeOut)
160 OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
161 (2 << retData->triedCount), retData->triedCount);
168 static void CACheckRetransmissionList(CARetransmission_t *context)
172 OIC_LOG(ERROR, TAG, "context is null");
177 ca_mutex_lock(context->threadMutex);
180 uint32_t len = u_arraylist_length(context->dataList);
182 for (i = 0; i < len; i++)
184 CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
191 uint64_t currentTime = OICGetCurrentTime(TIME_IN_US);
193 if (CACheckTimeout(currentTime, retData))
195 // #2. if time's up, send the data.
196 if (NULL != context->dataSendMethod)
198 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
200 context->dataSendMethod(retData->endpoint, retData->pdu,
201 retData->size, retData->dataType);
204 // #3. increase the retransmission count and update timestamp.
205 retData->timeStamp = currentTime;
206 retData->triedCount++;
209 // #4. if tried count is max, remove the retransmission data from list.
210 if (retData->triedCount >= context->config.tryingCount)
212 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
213 if (NULL == removedData)
215 OIC_LOG(ERROR, TAG, "Removed data is NULL");
217 ca_mutex_unlock(context->threadMutex);
220 OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
221 "msgid=%d", removedData->messageId);
223 // callback for retransmit timeout
224 if (NULL != context->timeoutCallback)
226 context->timeoutCallback(removedData->endpoint, removedData->pdu,
230 CAFreeEndpoint(removedData->endpoint);
231 OICFree(removedData->pdu);
233 OICFree(removedData);
235 // modify loop value.
236 len = u_arraylist_length(context->dataList);
242 ca_mutex_unlock(context->threadMutex);
245 void CARetransmissionBaseRoutine(void *threadValue)
247 OIC_LOG(DEBUG, TAG, "retransmission main thread start");
249 CARetransmission_t *context = (CARetransmission_t *) threadValue;
253 OIC_LOG(ERROR, TAG, "thread data passing error");
259 if (true == context->isStop)
261 OIC_LOG(DEBUG, TAG, "thread stopped");
264 CACheckRetransmissionList(context);
267 while (!context->isStop)
270 ca_mutex_lock(context->threadMutex);
272 if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
274 // if list is empty, thread will wait
275 OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
278 ca_cond_wait(context->threadCond, context->threadMutex);
280 OIC_LOG(DEBUG, TAG, "wake up..");
282 else if (!context->isStop)
284 // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
285 OIC_LOG_V(DEBUG, TAG, "wait..(%lld)microseconds",
286 RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
289 uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
290 ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
294 // we are stopping, so we want to unlock and finish stopping
298 ca_mutex_unlock(context->threadMutex);
306 CACheckRetransmissionList(context);
309 ca_mutex_lock(context->threadMutex);
310 ca_cond_signal(context->threadCond);
311 ca_mutex_unlock(context->threadMutex);
314 OIC_LOG(DEBUG, TAG, "retransmission main thread end");
318 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
319 ca_thread_pool_t handle,
320 CADataSendMethod_t retransmissionSendMethod,
321 CATimeoutCallback_t timeoutCallback,
322 CARetransmissionConfig_t* config)
326 OIC_LOG(ERROR, TAG, "thread instance is empty");
327 return CA_STATUS_INVALID_PARAM;
329 #ifndef SINGLE_THREAD
332 OIC_LOG(ERROR, TAG, "thread pool handle is empty");
333 return CA_STATUS_INVALID_PARAM;
336 OIC_LOG(DEBUG, TAG, "thread initialize");
338 memset(context, 0, sizeof(CARetransmission_t));
340 CARetransmissionConfig_t cfg = { .supportType = DEFAULT_RETRANSMISSION_TYPE,
341 .tryingCount = DEFAULT_RETRANSMISSION_COUNT };
348 // set send thread data
349 context->threadPool = handle;
350 context->threadMutex = ca_mutex_new();
351 context->threadCond = ca_cond_new();
352 context->dataSendMethod = retransmissionSendMethod;
353 context->timeoutCallback = timeoutCallback;
354 context->config = cfg;
355 context->isStop = false;
356 context->dataList = u_arraylist_create();
361 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
362 const CAEndpoint_t *endpoint,
363 CADataType_t dataType,
364 const void *pdu, uint32_t size)
366 if (NULL == context || NULL == endpoint || NULL == pdu)
368 OIC_LOG(ERROR, TAG, "invalid parameter");
369 return CA_STATUS_INVALID_PARAM;
372 // #0. check support transport type
373 if (!(context->config.supportType & endpoint->adapter))
375 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
376 return CA_NOT_SUPPORTED;
379 // #1. check PDU method type and get message id.
380 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
381 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
383 OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d, msgid=%d", type, messageId);
385 if (CA_MSG_CONFIRM != type)
387 OIC_LOG(DEBUG, TAG, "not supported message type");
388 return CA_NOT_SUPPORTED;
391 // create retransmission data
392 CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
393 1, sizeof(CARetransmissionData_t));
397 OIC_LOG(ERROR, TAG, "memory error");
398 return CA_MEMORY_ALLOC_FAILED;
402 void *pduData = (void *) OICMalloc(size);
406 OIC_LOG(ERROR, TAG, "memory error");
407 return CA_MEMORY_ALLOC_FAILED;
409 memcpy(pduData, pdu, size);
411 // clone remote endpoint
412 CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
413 if (NULL == remoteEndpoint)
417 OIC_LOG(ERROR, TAG, "memory error");
418 return CA_MEMORY_ALLOC_FAILED;
421 // #2. add additional information. (time stamp, retransmission count...)
422 retData->timeStamp = OICGetCurrentTime(TIME_IN_US);
423 #ifndef SINGLE_THREAD
424 retData->timeout = CAGetTimeoutValue();
426 retData->triedCount = 0;
427 retData->messageId = messageId;
428 retData->endpoint = remoteEndpoint;
429 retData->pdu = pduData;
430 retData->size = size;
431 retData->dataType = dataType;
432 #ifndef SINGLE_THREAD
434 ca_mutex_lock(context->threadMutex);
437 uint32_t len = u_arraylist_length(context->dataList);
439 // #3. add data into list
440 for (i = 0; i < len; i++)
442 CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
444 if (NULL == currData)
450 if (NULL != currData->endpoint && currData->messageId == messageId
451 && (currData->endpoint->adapter == endpoint->adapter))
453 OIC_LOG(ERROR, TAG, "Duplicate message ID");
456 ca_mutex_unlock(context->threadMutex);
460 OICFree(remoteEndpoint);
461 return CA_STATUS_FAILED;
465 u_arraylist_add(context->dataList, (void *) retData);
468 ca_cond_signal(context->threadCond);
471 ca_mutex_unlock(context->threadMutex);
474 u_arraylist_add(context->dataList, (void *) retData);
476 CACheckRetransmissionList(context);
481 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
482 const CAEndpoint_t *endpoint, const void *pdu,
483 uint32_t size, void **retransmissionPdu)
485 OIC_LOG(DEBUG, TAG, "IN");
486 if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
488 OIC_LOG(ERROR, TAG, "invalid parameter");
489 return CA_STATUS_INVALID_PARAM;
492 // #0. check support transport type
493 if (!(context->config.supportType & endpoint->adapter))
495 OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
499 // #1. check PDU method type and get message id.
500 // ACK, RST --> remove the CON data
501 CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
502 uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
503 CAResponseResult_t code = CAGetCodeFromPduBinaryData(pdu, size);
505 OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d, code=%d",
506 type, messageId, code);
508 if (((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
509 || (CA_MSG_RESET == type && CA_EMPTY != code))
515 ca_mutex_lock(context->threadMutex);
516 uint32_t len = u_arraylist_length(context->dataList);
520 for (i = 0; i < len; i++)
522 CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
523 context->dataList, i);
531 if (NULL != retData->endpoint && retData->messageId == messageId
532 && (retData->endpoint->adapter == endpoint->adapter))
534 // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
535 // if retransmission was finish..token will be unavailable.
536 if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
538 OIC_LOG(DEBUG, TAG, "code is CA_EMPTY");
540 if (NULL == retData->pdu)
542 OIC_LOG(ERROR, TAG, "retData->pdu is null");
545 ca_mutex_unlock(context->threadMutex);
547 return CA_STATUS_FAILED;
551 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
552 if ((*retransmissionPdu) == NULL)
555 OIC_LOG(ERROR, TAG, "memory error");
558 ca_mutex_unlock(context->threadMutex);
560 return CA_MEMORY_ALLOC_FAILED;
562 memcpy((*retransmissionPdu), retData->pdu, retData->size);
565 // #2. remove data from list
566 CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
567 if (NULL == removedData)
569 OIC_LOG(ERROR, TAG, "Removed data is NULL");
572 ca_mutex_unlock(context->threadMutex);
574 return CA_STATUS_FAILED;
577 OIC_LOG_V(DEBUG, TAG, "remove RTCON data!!, msgid=%d", messageId);
579 CAFreeEndpoint(removedData->endpoint);
580 OICFree(removedData->pdu);
581 OICFree(removedData);
588 ca_mutex_unlock(context->threadMutex);
590 OIC_LOG(DEBUG, TAG, "OUT");
594 CAResult_t CARetransmissionStop(CARetransmission_t *context)
598 OIC_LOG(ERROR, TAG, "context is empty..");
599 return CA_STATUS_INVALID_PARAM;
602 OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
605 ca_mutex_lock(context->threadMutex);
608 context->isStop = true;
611 ca_cond_signal(context->threadCond);
613 ca_cond_wait(context->threadCond, context->threadMutex);
616 ca_mutex_unlock(context->threadMutex);
621 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
625 OIC_LOG(ERROR, TAG, "context is empty..");
626 return CA_STATUS_INVALID_PARAM;
629 OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
631 ca_mutex_free(context->threadMutex);
632 context->threadMutex = NULL;
633 ca_cond_free(context->threadCond);
634 u_arraylist_free(&context->dataList);