Fixed build warnings due to assert, unused function, time
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / caretransmission.c
1 /******************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  ******************************************************************/
20
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
26 //
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
31
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
36 //
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
42 #endif
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 #ifndef SINGLE_THREAD
49 #include <unistd.h>
50 #include <time.h>
51 #include <sys/time.h>
52 #endif
53
54 #if defined(__ANDROID__)
55 #include <linux/time.h>
56 #endif
57
58 #include "caretransmission.h"
59 #include "caremotehandler.h"
60 #include "caprotocolmessage.h"
61 #include "oic_malloc.h"
62 #include "logger.h"
63
64 #define TAG "CA_RETRANS"
65
66 typedef struct
67 {
68     uint64_t timeStamp;                 /**< last sent time. microseconds */
69 #ifndef SINGLE_THREAD
70     uint64_t timeout;                   /**< timeout value. microseconds */
71 #endif
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;
78
79 static const uint64_t USECS_PER_SEC = 1000000;
80
81 /**
82  * @brief   getCurrent monotonic time
83  * @return  current time in microseconds
84  */
85 uint64_t getCurrentTimeInMicroSeconds();
86
87 #ifndef SINGLE_THREAD
88 /**
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.
94  */
95 static uint64_t CAGetTimeoutValue()
96 {
97     return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
98             (uint64_t) 1000;
99 }
100
101 CAResult_t CARetransmissionStart(CARetransmission_t *context)
102 {
103     if (NULL == context)
104     {
105         OIC_LOG(ERROR, TAG, "context is empty");
106         return CA_STATUS_INVALID_PARAM;
107     }
108
109     if (NULL == context->threadPool)
110     {
111         OIC_LOG(ERROR, TAG, "thread pool handle is empty..");
112         return CA_STATUS_INVALID_PARAM;
113     }
114
115     CAResult_t res = ca_thread_pool_add_task(context->threadPool, CARetransmissionBaseRoutine,
116                                              context);
117
118     if (CA_STATUS_OK != res)
119     {
120         OIC_LOG(ERROR, TAG, "thread pool add task error(send thread).");
121         return res;
122     }
123
124     return res;
125 }
126 #endif
127
128 /**
129  * @brief   check timeout routine
130  * @param   currentTime     [IN]microseconds
131  * @param   retData         [IN]retransmission data
132  * @return  true if the timeout period has elapsed, false otherwise
133  */
134 static bool CACheckTimeout(uint64_t currentTime, CARetransmissionData_t *retData)
135 {
136 #ifndef SINGLE_THREAD
137     // #1. calculate timeout
138     uint32_t milliTimeoutValue = retData->timeout * 0.001;
139     uint64_t timeout = (milliTimeoutValue << retData->triedCount) * (uint64_t) 1000;
140
141     if (currentTime >= retData->timeStamp + timeout)
142     {
143         OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%ld)",
144                   timeout, retData->triedCount);
145         return true;
146     }
147 #else
148     // #1. calculate timeout
149     uint64_t timeOut = (2 << retData->triedCount) * 1000000;
150
151     if (currentTime >= retData->timeStamp + timeOut)
152     {
153         OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d",
154                   (2 << retData->triedCount), retData->triedCount);
155         return true;
156     }
157 #endif
158     return false;
159 }
160
161 static void CACheckRetransmissionList(CARetransmission_t *context)
162 {
163     if (NULL == context)
164     {
165         OIC_LOG(ERROR, TAG, "context is null");
166         return;
167     }
168
169     // mutex lock
170     ca_mutex_lock(context->threadMutex);
171
172     uint32_t i = 0;
173     uint32_t len = u_arraylist_length(context->dataList);
174
175     for (i = 0; i < len; i++)
176     {
177         CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
178
179         if (NULL == retData)
180         {
181             continue;
182         }
183
184         uint64_t currentTime = getCurrentTimeInMicroSeconds();
185
186         if (CACheckTimeout(currentTime, retData))
187         {
188             // #2. if time's up, send the data.
189             if (NULL != context->dataSendMethod)
190             {
191                 OIC_LOG_V(DEBUG, TAG, "retransmission CON data!!, msgid=%d",
192                           retData->messageId);
193                 context->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
194             }
195
196             // #3. increase the retransmission count and update timestamp.
197             retData->timeStamp = currentTime;
198             retData->triedCount++;
199         }
200
201         // #4. if tried count is max, remove the retransmission data from list.
202         if (retData->triedCount >= context->config.tryingCount)
203         {
204             CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
205             if (NULL == removedData)
206             {
207                 OIC_LOG(ERROR, TAG, "Removed data is NULL");
208                 // mutex unlock
209                 ca_mutex_unlock(context->threadMutex);
210                 return;
211             }
212             OIC_LOG_V(DEBUG, TAG, "max trying count, remove RTCON data,"
213                       "msgid=%d", removedData->messageId);
214
215             // callback for retransmit timeout
216             if (NULL != context->timeoutCallback)
217             {
218                 context->timeoutCallback(removedData->endpoint, removedData->pdu,
219                                          removedData->size);
220             }
221
222             CAFreeEndpoint(removedData->endpoint);
223             OICFree(removedData->pdu);
224
225             OICFree(removedData);
226
227             // modify loop value.
228             len = u_arraylist_length(context->dataList);
229             --i;
230         }
231     }
232
233     // mutex unlock
234     ca_mutex_unlock(context->threadMutex);
235 }
236
237 void CARetransmissionBaseRoutine(void *threadValue)
238 {
239     OIC_LOG(DEBUG, TAG, "retransmission main thread start");
240
241     CARetransmission_t *context = (CARetransmission_t *) threadValue;
242
243     if (NULL == context)
244     {
245         OIC_LOG(ERROR, TAG, "thread data passing error");
246
247         return;
248     }
249
250 #ifdef SINGLE_THREAD
251     if (true == context->isStop)
252     {
253         OIC_LOG(DEBUG, TAG, "thread stopped");
254         return;
255     }
256     CACheckRetransmissionList(context);
257 #else
258
259     while (!context->isStop)
260     {
261         // mutex lock
262         ca_mutex_lock(context->threadMutex);
263
264         if (!context->isStop && u_arraylist_length(context->dataList) <= 0)
265         {
266             // if list is empty, thread will wait
267             OIC_LOG(DEBUG, TAG, "wait..there is no retransmission data.");
268
269             // wait
270             ca_cond_wait(context->threadCond, context->threadMutex);
271
272             OIC_LOG(DEBUG, TAG, "wake up..");
273         }
274         else if (!context->isStop)
275         {
276             // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
277             OIC_LOG_V(DEBUG, TAG, "wait..(%ld)microseconds",
278                       RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC);
279
280             // wait
281             uint64_t absTime = RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) USECS_PER_SEC;
282             ca_cond_wait_for(context->threadCond, context->threadMutex, absTime );
283         }
284         else
285         {
286             // we are stopping, so we want to unlock and finish stopping
287         }
288
289         // mutex unlock
290         ca_mutex_unlock(context->threadMutex);
291
292         // check stop flag
293         if (context->isStop)
294         {
295             continue;
296         }
297
298         CACheckRetransmissionList(context);
299     }
300
301     ca_mutex_lock(context->threadMutex);
302     ca_cond_signal(context->threadCond);
303     ca_mutex_unlock(context->threadMutex);
304
305 #endif
306     OIC_LOG(DEBUG, TAG, "retransmission main thread end");
307
308 }
309
310 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
311                                       ca_thread_pool_t handle,
312                                       CADataSendMethod_t retransmissionSendMethod,
313                                       CATimeoutCallback_t timeoutCallback,
314                                       CARetransmissionConfig_t* config)
315 {
316     if (NULL == context)
317     {
318         OIC_LOG(ERROR, TAG, "thread instance is empty");
319         return CA_STATUS_INVALID_PARAM;
320     }
321 #ifndef SINGLE_THREAD
322     if (NULL == handle)
323     {
324         OIC_LOG(ERROR, TAG, "thread pool handle is empty");
325         return CA_STATUS_INVALID_PARAM;
326     }
327 #endif
328     OIC_LOG(DEBUG, TAG, "thread initialize");
329
330     memset(context, 0, sizeof(CARetransmission_t));
331
332     CARetransmissionConfig_t cfg = { 0 };
333
334     if (NULL == config)
335     {
336         // setDefault
337         cfg.supportType = DEFAULT_RETRANSMISSION_TYPE;
338         cfg.tryingCount = DEFAULT_RETRANSMISSION_COUNT;
339     }
340     else
341     {
342         cfg = *config;
343     }
344
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();
354
355     return CA_STATUS_OK;
356 }
357
358 CAResult_t CARetransmissionSentData(CARetransmission_t *context,
359                                     const CAEndpoint_t *endpoint,
360                                     const void *pdu, uint32_t size)
361 {
362     if (NULL == context || NULL == endpoint || NULL == pdu)
363     {
364         OIC_LOG(ERROR, TAG, "invalid parameter");
365         return CA_STATUS_INVALID_PARAM;
366     }
367
368     // #0. check support transport type
369     if (!(context->config.supportType & endpoint->adapter))
370     {
371         OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
372         return CA_NOT_SUPPORTED;
373     }
374
375     // #1. check PDU method type and get message id.
376     CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
377     uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
378
379     OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d, msgid=%d", type, messageId);
380
381     if (CA_MSG_CONFIRM != type)
382     {
383         OIC_LOG(DEBUG, TAG, "not supported message type");
384         return CA_NOT_SUPPORTED;
385     }
386
387     // create retransmission data
388     CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
389                                           1, sizeof(CARetransmissionData_t));
390
391     if (NULL == retData)
392     {
393         OIC_LOG(ERROR, TAG, "memory error");
394         return CA_MEMORY_ALLOC_FAILED;
395     }
396
397     // copy PDU data
398     void *pduData = (void *) OICMalloc(size);
399     if (NULL == pduData)
400     {
401         OICFree(retData);
402         OIC_LOG(ERROR, TAG, "memory error");
403         return CA_MEMORY_ALLOC_FAILED;
404     }
405     memcpy(pduData, pdu, size);
406
407     // clone remote endpoint
408     CAEndpoint_t *remoteEndpoint = CACloneEndpoint(endpoint);
409     if (NULL == remoteEndpoint)
410     {
411         OICFree(retData);
412         OICFree(pduData);
413         OIC_LOG(ERROR, TAG, "memory error");
414         return CA_MEMORY_ALLOC_FAILED;
415     }
416
417     // #2. add additional information. (time stamp, retransmission count...)
418     retData->timeStamp = getCurrentTimeInMicroSeconds();
419 #ifndef SINGLE_THREAD
420     retData->timeout = CAGetTimeoutValue();
421 #endif
422     retData->triedCount = 0;
423     retData->messageId = messageId;
424     retData->endpoint = remoteEndpoint;
425     retData->pdu = pduData;
426     retData->size = size;
427 #ifndef SINGLE_THREAD
428     // mutex lock
429     ca_mutex_lock(context->threadMutex);
430
431     uint32_t i = 0;
432     uint32_t len = u_arraylist_length(context->dataList);
433
434     // #3. add data into list
435     for (i = 0; i < len; i++)
436     {
437         CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
438
439         if (NULL == currData)
440         {
441             continue;
442         }
443
444         // found index
445         if (NULL != currData->endpoint && currData->messageId == messageId
446             && (currData->endpoint->adapter == endpoint->adapter))
447         {
448             OIC_LOG(ERROR, TAG, "Duplicate message ID");
449
450             // mutex unlock
451             ca_mutex_unlock(context->threadMutex);
452
453             OICFree(retData);
454             OICFree(pduData);
455             OICFree(remoteEndpoint);
456             return CA_STATUS_FAILED;
457         }
458     }
459
460     u_arraylist_add(context->dataList, (void *) retData);
461
462     // notify the thread
463     ca_cond_signal(context->threadCond);
464
465     // mutex unlock
466     ca_mutex_unlock(context->threadMutex);
467
468 #else
469     u_arraylist_add(context->dataList, (void *) retData);
470
471     CACheckRetransmissionList(context);
472 #endif
473     return CA_STATUS_OK;
474 }
475
476 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
477                                         const CAEndpoint_t *endpoint, const void *pdu,
478                                         uint32_t size, void **retransmissionPdu)
479 {
480     OIC_LOG(DEBUG, TAG, "IN");
481     if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
482     {
483         OIC_LOG(ERROR, TAG, "invalid parameter");
484         return CA_STATUS_INVALID_PARAM;
485     }
486
487     // #0. check support transport type
488     if (!(context->config.supportType & endpoint->adapter))
489     {
490         OIC_LOG_V(DEBUG, TAG, "not supported transport type=%d", endpoint->adapter);
491         return CA_STATUS_OK;
492     }
493
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
499     OIC_LOG_V(DEBUG, TAG, "received pdu, msgtype=%d, msgid=%d", type, messageId);
500
501     if ((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type))
502     {
503         return CA_STATUS_OK;
504     }
505
506     // mutex lock
507     ca_mutex_lock(context->threadMutex);
508     uint32_t len = u_arraylist_length(context->dataList);
509
510     // find index
511     uint32_t i;
512     for (i = 0; i < len; i++)
513     {
514         CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
515                 context->dataList, i);
516
517         if (NULL == retData)
518         {
519             continue;
520         }
521
522         // found index
523         if (NULL != retData->endpoint && retData->messageId == messageId
524             && (retData->endpoint->adapter == endpoint->adapter))
525         {
526             // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
527             // if retransmission was finish..token will be unavailable.
528             if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
529             {
530                 OIC_LOG(DEBUG, TAG, "code is CA_EMPTY");
531
532                 if (NULL == retData->pdu)
533                 {
534                     OIC_LOG(ERROR, TAG, "retData->pdu is null");
535                     OICFree(retData);
536                     // mutex unlock
537                     ca_mutex_unlock(context->threadMutex);
538
539                     return CA_STATUS_FAILED;
540                 }
541
542                 // copy PDU data
543                 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
544                 if ((*retransmissionPdu) == NULL)
545                 {
546                     OICFree(retData);
547                     OIC_LOG(ERROR, TAG, "memory error");
548
549                     // mutex unlock
550                     ca_mutex_unlock(context->threadMutex);
551
552                     return CA_MEMORY_ALLOC_FAILED;
553                 }
554                 memcpy((*retransmissionPdu), retData->pdu, retData->size);
555             }
556
557             // #2. remove data from list
558             CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
559             if (NULL == removedData)
560             {
561                 OIC_LOG(ERROR, TAG, "Removed data is NULL");
562
563                 // mutex unlock
564                 ca_mutex_unlock(context->threadMutex);
565
566                 return CA_STATUS_FAILED;
567             }
568
569             OIC_LOG_V(DEBUG, TAG, "remove RTCON data!!, msgid=%d", messageId);
570
571             CAFreeEndpoint(removedData->endpoint);
572             OICFree(removedData->pdu);
573             OICFree(removedData);
574
575             break;
576         }
577     }
578
579     // mutex unlock
580     ca_mutex_unlock(context->threadMutex);
581
582     OIC_LOG(DEBUG, TAG, "OUT");
583     return CA_STATUS_OK;
584 }
585
586 CAResult_t CARetransmissionStop(CARetransmission_t *context)
587 {
588     if (NULL == context)
589     {
590         OIC_LOG(ERROR, TAG, "context is empty..");
591         return CA_STATUS_INVALID_PARAM;
592     }
593
594     OIC_LOG(DEBUG, TAG, "retransmission stop request!!");
595
596     // mutex lock
597     ca_mutex_lock(context->threadMutex);
598
599     // set stop flag
600     context->isStop = true;
601
602     // notify the thread
603     ca_cond_signal(context->threadCond);
604
605     ca_cond_wait(context->threadCond, context->threadMutex);
606
607     // mutex unlock
608     ca_mutex_unlock(context->threadMutex);
609
610     return CA_STATUS_OK;
611 }
612
613 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
614 {
615     if (NULL == context)
616     {
617         OIC_LOG(ERROR, TAG, "context is empty..");
618         return CA_STATUS_INVALID_PARAM;
619     }
620
621     OIC_LOG(DEBUG, TAG, "retransmission context destroy..");
622
623     ca_mutex_free(context->threadMutex);
624     context->threadMutex = NULL;
625     ca_cond_free(context->threadCond);
626     u_arraylist_free(&context->dataList);
627
628     return CA_STATUS_OK;
629 }
630
631 uint64_t getCurrentTimeInMicroSeconds()
632 {
633     OIC_LOG(DEBUG, TAG, "IN");
634     uint64_t currentTime = 0;
635
636 #ifdef __ANDROID__
637     struct timespec getTs;
638
639     clock_gettime(CLOCK_MONOTONIC, &getTs);
640
641     currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
642     OIC_LOG_V(DEBUG, TAG, "current time = %ld", currentTime);
643 #elif defined __ARDUINO__
644     currentTime = millis() * 1000;
645     OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
646 #else
647 #if _POSIX_TIMERS > 0
648     struct timespec ts;
649     clock_gettime(CLOCK_MONOTONIC, &ts);
650     currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
651 #else
652     struct timeval tv;
653     gettimeofday(&tv, NULL);
654     currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
655 #endif
656 #endif
657
658     OIC_LOG(DEBUG, TAG, "OUT");
659     return currentTime;
660 }