d7d9dbae66cd5072c7eeb472a270010f6d5563b8
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / caretransmission_singlethread.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 #include "caretransmission_singlethread.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include "caremotehandler.h"
27 #include "caprotocolmessage.h"
28 #include "oic_malloc.h"
29 #include "logger.h"
30
31 #ifndef __ARDUINO__
32 #include <sys/time.h>
33 #endif
34
35 #define TAG "RT"
36
37 typedef struct
38 {
39     /** last sent time. microseconds **/
40     uint64_t timeStamp;
41
42     /** retransmission count **/
43     uint8_t triedCount;
44
45     /** coap PDU message id **/
46     uint16_t messageId;
47
48     /** remote endpoint **/
49     CARemoteEndpoint_t *endpoint;
50
51     /** coap PDU **/
52     void *pdu;
53
54     /** coap PDU size**/
55     uint32_t size;
56
57 } CARetransmissionData_t;
58
59 static CARetransmission_t *g_retransmissionPtr = NULL;
60
61 /**
62  * getCurrent monotonic time.
63  *
64  * @return current time in microseconds.
65  */
66 uint64_t getCurrentTimeInMicroSeconds();
67
68 /**
69  * @brief   check timeout routine
70  * @param   currentTime     [IN]microseconds
71  * @param   timeStamp       [IN]microseconds
72  * @param   triedCount      [IN]Number of retransmission tried.
73  * @return  true if the timeout period has elapsed, false otherwise.
74  */
75 static bool CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint8_t triedCount)
76 {
77     OIC_LOG(DEBUG, TAG, "IN");
78     // #1. calculate timeout
79     uint64_t timeOut = (2 << triedCount) * 1000000;
80
81     if (currentTime >= timeStamp + timeOut)
82     {
83         OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d", (2 << triedCount), triedCount);
84         return true;
85     }
86
87     OIC_LOG(DEBUG, TAG, "OUT");
88     return false;
89 }
90
91 void CACheckRetransmissionList()
92 {
93     uint32_t len = u_arraylist_length(g_retransmissionPtr->dataList);
94
95     OIC_LOG_V(DEBUG, TAG, "len=%d", len);
96     for (uint32_t i = 0; i < len; i++)
97     {
98         CARetransmissionData_t *retData =
99                 (CARetransmissionData_t *) u_arraylist_get(g_retransmissionPtr->dataList, i);
100
101         if (NULL == retData)
102         {
103             continue;
104         }
105
106         uint64_t currentTime = getCurrentTimeInMicroSeconds();
107
108         OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
109         if (CACheckTimeout(currentTime, retData->timeStamp, retData->triedCount))
110         {
111
112             OIC_LOG(DEBUG, TAG, "RTdata-Success");
113             // #2. if time's up, send the data.
114             if (NULL != g_retransmissionPtr->dataSendMethod)
115             {
116                 OIC_LOG_V(DEBUG, TAG, "retry CON data-msgid=%d", retData->messageId);
117                 g_retransmissionPtr->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
118             }
119
120             // #3. increase the retransmission count and update timestamp.
121             retData->timeStamp = currentTime;
122             retData->triedCount++;
123         }
124
125         // #4. if tried count is max, remove the retransmission data from list.
126         if (retData->triedCount >= g_retransmissionPtr->config.tryingCount)
127         {
128             CARetransmissionData_t *removedData = (CARetransmissionData_t *) u_arraylist_remove(
129                     g_retransmissionPtr->dataList, i);
130             if (NULL == removedData)
131             {
132                 OIC_LOG(ERROR, TAG, "Removed data is NULL");
133                 return;
134             }
135
136             OIC_LOG(DEBUG, TAG, "max trycount rchd");
137
138             OIC_LOG_V(DEBUG, TAG, "max trycount, remove retransmission CON data!!, messageid=%d",
139                       removedData->messageId);
140
141             // callback for retransmit timeout
142             if (NULL != g_retransmissionPtr->timeoutCallback)
143             {
144                 g_retransmissionPtr->timeoutCallback(removedData->endpoint, removedData->pdu,
145                                                      removedData->size);
146             }
147
148             CADestroyRemoteEndpointInternal(removedData->endpoint);
149             OICFree(removedData->pdu);
150
151             OICFree(removedData);
152
153             // modify loop value.
154             len = u_arraylist_length(g_retransmissionPtr->dataList);
155             --i;
156         }
157     }
158 }
159
160 void CARetransmissionBaseRoutine(void *threadValue)
161 {
162     CARetransmission_t *context = (CARetransmission_t *) threadValue;
163
164     if (NULL == context)
165     {
166         OIC_LOG(ERROR, TAG, "cnxt null");
167         return;
168     }
169
170     if (true == context->isStop)
171     {
172         OIC_LOG(DEBUG, TAG, "thread stopped");
173         return;
174     }
175     g_retransmissionPtr = context;
176     CACheckRetransmissionList();
177 }
178
179 CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
180                                       CADataSendMethod_t retransmissionSendMethod,
181                                       CATimeoutCallback_t timeoutCallback,
182                                       CARetransmissionConfig_t *config)
183 {
184     OIC_LOG(DEBUG, TAG, "IN");
185     if (NULL == context)
186     {
187         OIC_LOG(ERROR, TAG, "cnxt null");
188         return CA_STATUS_INVALID_PARAM;
189     }
190
191     memset(context, 0, sizeof(CARetransmission_t));
192
193     CARetransmissionConfig_t cfg = {};
194
195     if (NULL == config)
196     {
197         // setDefault
198         cfg.supportType = (CATransportType_t) DEFAULT_RETRANSMISSION_TYPE;
199         cfg.tryingCount = DEFAULT_RETRANSMISSION_COUNT;
200     }
201     else
202     {
203         cfg = *config;
204     }
205
206     // set send thread data
207     context->dataSendMethod = retransmissionSendMethod;
208     context->timeoutCallback = timeoutCallback;
209     context->config = cfg;
210     context->isStop = false;
211     context->dataList = u_arraylist_create();
212
213     // Enable TimedAction for CACheckRetransmissionList API
214     g_retransmissionPtr = context;
215     OIC_LOG(DEBUG, TAG, "OUT");
216     return CA_STATUS_OK;
217 }
218
219 CAResult_t CARetransmissionSentData(CARetransmission_t *context, const CARemoteEndpoint_t *endpoint,
220                                     const void *pdu, uint32_t size)
221 {
222     OIC_LOG(DEBUG, TAG, "IN");
223     if (NULL == context || NULL == endpoint || NULL == pdu)
224     {
225         OIC_LOG(ERROR, TAG, "error");
226         return CA_STATUS_INVALID_PARAM;
227     }
228
229     // #0. check support connectivity type
230     if (!(context->config.supportType & endpoint->transportType))
231     {
232         OIC_LOG(ERROR, TAG, "error");
233         OIC_LOG_V(ERROR, TAG, "not supported conntype=%d", endpoint->transportType);
234         return CA_NOT_SUPPORTED;
235     }
236
237     // #1. check PDU method type and get message id.
238     CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
239     uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
240
241     OIC_LOG_V(DEBUG, TAG, "sent pdu, msgtype=%d,msgid=%d", type, messageId);
242
243     if (CA_MSG_CONFIRM != type)
244     {
245         OIC_LOG(DEBUG, TAG, "not supported message type");
246         return CA_NOT_SUPPORTED;
247     }
248
249     // create retransmission data
250     CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
251             1, sizeof(CARetransmissionData_t));
252
253     if (NULL == retData)
254     {
255         OIC_LOG(ERROR, TAG, "error");
256         return CA_MEMORY_ALLOC_FAILED;
257     }
258
259     // copy PDU data
260     void *pduData = (void *) OICMalloc(size);
261     if (NULL == pduData)
262     {
263         OICFree(retData);
264         OIC_LOG(ERROR, TAG, "error");
265         return CA_MEMORY_ALLOC_FAILED;
266     }
267     memcpy(pduData, pdu, size);
268
269     // clone remote endpoint
270     CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(endpoint);
271     if (NULL == remoteEndpoint)
272     {
273         OICFree(retData);
274         OICFree(pduData);
275         OIC_LOG(ERROR, TAG, "error");
276         return CA_MEMORY_ALLOC_FAILED;
277     }
278
279     // #2. add additional information. (time stamp, retransmission count...)
280     retData->timeStamp = getCurrentTimeInMicroSeconds();
281     retData->triedCount = 0;
282     retData->messageId = messageId;
283     retData->endpoint = remoteEndpoint;
284     retData->pdu = pduData;
285     retData->size = size;
286
287     // #3. add data into list
288     u_arraylist_add(context->dataList, (void *) retData);
289
290     // #4. Initiate Re-transmission for added entry
291     g_retransmissionPtr = context;
292     CACheckRetransmissionList();
293     OIC_LOG(DEBUG, TAG, "OUT");
294     return CA_STATUS_OK;
295 }
296
297 CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
298                                         const CARemoteEndpoint_t *endpoint, const void *pdu,
299                                         uint32_t size, void **retransmissionPdu)
300 {
301     OIC_LOG(DEBUG, TAG, "IN");
302     if (NULL == context || NULL == endpoint || NULL == pdu || NULL == retransmissionPdu)
303     {
304         OIC_LOG(ERROR, TAG, "error");
305         return CA_STATUS_INVALID_PARAM;
306     }
307
308     // #0. check support connectivity type
309     if (!(context->config.supportType & endpoint->transportType))
310     {
311         OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->transportType);
312         return CA_STATUS_OK;
313     }
314
315     // #1. check PDU method type and get message id.
316     // ACK, RST --> remove the CON data
317     CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
318     uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
319
320     OIC_LOG_V(DEBUG, TAG, "recv pdu, msgtype=%d,msgid=%d", type, messageId);
321
322     if (CA_MSG_ACKNOWLEDGE != type && CA_MSG_RESET != type)
323     {
324         return CA_STATUS_OK;
325     }
326
327     uint32_t len = u_arraylist_length(context->dataList);
328
329     // find index
330     for (uint32_t i = 0; i < len; i++)
331     {
332         CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get(
333                 context->dataList, i);
334
335         if (NULL == retData)
336         {
337             continue;
338         }
339
340         // found index
341         if (NULL != retData->endpoint && retData->messageId == messageId
342             && (retData->endpoint->transportType == endpoint->transportType))
343         {
344             // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
345             // if retransmission was finish..token will be unavailable.
346             if (CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
347             {
348                 OIC_LOG(DEBUG, TAG, "CA_EMPTY");
349
350                 if (NULL == retData->pdu)
351                 {
352                     OIC_LOG(ERROR, TAG, "retData->pdu is null");
353                     OICFree(retData);
354                     return CA_STATUS_FAILED;
355                 }
356
357                 // copy PDU data
358                 (*retransmissionPdu) = (void *) OICCalloc(1, retData->size);
359                 if (NULL == (*retransmissionPdu))
360                 {
361                     OICFree(retData);
362                     OIC_LOG(ERROR, TAG, "error");
363                     return CA_MEMORY_ALLOC_FAILED;
364                 }
365                 memcpy((*retransmissionPdu), retData->pdu, retData->size);
366             }
367
368             // #2. remove data from list
369             CARetransmissionData_t *removedData = (CARetransmissionData_t *) u_arraylist_remove(
370                     context->dataList, i);
371             if (NULL == removedData)
372             {
373                 OIC_LOG(ERROR, TAG, "Removed data is NULL");
374                 return CA_STATUS_FAILED;
375             }
376
377             OIC_LOG_V(DEBUG, TAG, "remove RTCON data, msgid=%d", messageId);
378
379             CADestroyRemoteEndpointInternal(removedData->endpoint);
380             OICFree(removedData->pdu);
381
382             OICFree(removedData);
383
384             break;
385         }
386     }
387
388     OIC_LOG(DEBUG, TAG, "OUT");
389     return CA_STATUS_OK;
390 }
391
392 CAResult_t CARetransmissionStop(CARetransmission_t *context)
393 {
394     OIC_LOG(DEBUG, TAG, "IN");
395     if (NULL == context)
396     {
397         OIC_LOG(ERROR, TAG, "error");
398         return CA_STATUS_INVALID_PARAM;
399     }
400
401     // set stop flag
402     context->isStop = true;
403     OIC_LOG(DEBUG, TAG, "OUT");
404     return CA_STATUS_OK;
405 }
406
407 CAResult_t CARetransmissionDestroy(CARetransmission_t *context)
408 {
409     OIC_LOG(DEBUG, TAG, "IN");
410     if (NULL == context)
411     {
412         OIC_LOG(ERROR, TAG, "error");
413         return CA_STATUS_INVALID_PARAM;
414     }
415
416     u_arraylist_free(&context->dataList);
417     OIC_LOG(DEBUG, TAG, "OUT");
418     return CA_STATUS_OK;
419 }
420
421 uint64_t getCurrentTimeInMicroSeconds()
422 {
423     OIC_LOG(DEBUG, TAG, "IN");
424     uint64_t currentTime = 0;
425
426 #ifdef __ARDUINO__
427     currentTime = millis() * 1000;
428
429     OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
430 #else
431     struct timeval tv;
432     gettimeofday(&tv, NULL);
433     currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
434 #endif
435
436     OIC_LOG(DEBUG, TAG, "OUT");
437     return currentTime;
438 }
439