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