Disable the Multicast Action in Mobile Network Case.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / cablockwisetransfer.c
1 /* ****************************************************************
2  *
3  * Copyright 2015 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 #define _BSD_SOURCE
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36
37 #include "caadapterutils.h"
38 #include "cainterface.h"
39 #include "camessagehandler.h"
40 #include "caremotehandler.h"
41 #include "cablockwisetransfer.h"
42 #include "oic_malloc.h"
43 #include "oic_string.h"
44 #include "octhread.h"
45 #include "logger.h"
46 #include "oic_time.h"
47
48 #define TAG "OIC_CA_BWT"
49
50 #define BLOCKWISE_OPTION_BUFFER    (sizeof(unsigned int))
51 #define BLOCK_NUMBER_IDX           4
52 #define BLOCK_M_BIT_IDX            3
53 #define PORT_LENGTH                2
54
55 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
56
57 #define BLOCK_DATA_TIMEOUT_SECONDS   (60 * 1)  // 1 minutes.
58 static const uint64_t USECS_PER_SEC = 1000000;
59
60 // context for block-wise transfer
61 static CABlockWiseContext_t g_context = { .sendThreadFunc = NULL,
62                                           .receivedThreadFunc = NULL,
63                                           .dataList = NULL };
64
65 static bool CACheckPayloadLength(const CAData_t *sendData)
66 {
67     size_t payloadLen = 0;
68     CAGetPayloadInfo(sendData, &payloadLen);
69
70     // check if message has to be transfered to a block
71     size_t maxBlockSize = BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE);
72     OIC_LOG_V(DEBUG, TAG, "payloadLen=%zu, maxBlockSize=%zu", payloadLen, maxBlockSize);
73
74     if (payloadLen <= maxBlockSize)
75     {
76         return false;
77     }
78
79     return true;
80 }
81
82 CAResult_t CAInitializeBlockWiseTransfer(CASendThreadFunc sendThreadFunc,
83                                          CAReceiveThreadFunc receivedThreadFunc)
84 {
85     OIC_LOG(DEBUG, TAG, "CAInitializeBlockWiseTransfer");
86
87     // set block-wise transfer context
88     if (!g_context.sendThreadFunc)
89     {
90         g_context.sendThreadFunc = sendThreadFunc;
91     }
92
93     if (!g_context.receivedThreadFunc)
94     {
95         g_context.receivedThreadFunc = receivedThreadFunc;
96     }
97
98     if (!g_context.dataList)
99     {
100         g_context.dataList = u_arraylist_create();
101     }
102
103     CAResult_t res = CAInitBlockWiseMutexVariables();
104     if (CA_STATUS_OK != res)
105     {
106         u_arraylist_free(&g_context.dataList);
107         g_context.dataList = NULL;
108         OIC_LOG(ERROR, TAG, "init has failed");
109     }
110
111     return res;
112 }
113
114 CAResult_t CATerminateBlockWiseTransfer()
115 {
116     OIC_LOG(DEBUG, TAG, "CATerminateBlockWiseTransfer");
117
118     if (g_context.dataList)
119     {
120         CARemoveAllBlockDataFromList();
121         u_arraylist_free(&g_context.dataList);
122     }
123
124     CATerminateBlockWiseMutexVariables();
125
126     return CA_STATUS_OK;
127 }
128
129 CAResult_t CAInitBlockWiseMutexVariables()
130 {
131     if (!g_context.blockDataListMutex)
132     {
133         g_context.blockDataListMutex = oc_mutex_new();
134         if (!g_context.blockDataListMutex)
135         {
136             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
137             return CA_STATUS_FAILED;
138         }
139     }
140
141     if (!g_context.blockDataSenderMutex)
142     {
143         g_context.blockDataSenderMutex = oc_mutex_new();
144         if (!g_context.blockDataSenderMutex)
145         {
146             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
147             CATerminateBlockWiseMutexVariables();
148             return CA_STATUS_FAILED;
149         }
150     }
151
152     return CA_STATUS_OK;
153 }
154
155 void CATerminateBlockWiseMutexVariables()
156 {
157     if (g_context.blockDataListMutex)
158     {
159         oc_mutex_free(g_context.blockDataListMutex);
160         g_context.blockDataListMutex = NULL;
161     }
162
163     if (g_context.blockDataSenderMutex)
164     {
165         oc_mutex_free(g_context.blockDataSenderMutex);
166         g_context.blockDataSenderMutex = NULL;
167     }
168 }
169
170 CAResult_t CASendBlockWiseData(const CAData_t *sendData)
171 {
172     VERIFY_NON_NULL(sendData, TAG, "sendData");
173
174     // check if message type is CA_MSG_RESET
175     if (sendData->requestInfo)
176     {
177         if (CA_MSG_RESET == sendData->requestInfo->info.type)
178         {
179             OIC_LOG(DEBUG, TAG, "reset message can't be sent to the block");
180             return CA_NOT_SUPPORTED;
181         }
182
183         /*
184          * Other uses of the Block options in conjunction with multicast
185          * messages are for further study.
186          */
187         if (sendData->requestInfo->isMulticast)
188         {
189             OIC_LOG(DEBUG, TAG, "multicast message can't be sent to the block");
190             return CA_NOT_SUPPORTED;
191         }
192     }
193     else if (sendData->responseInfo)
194     {
195         if (CA_MSG_RESET == sendData->responseInfo->info.type)
196         {
197             OIC_LOG(DEBUG, TAG, "reset message can't be sent to the block");
198             return CA_NOT_SUPPORTED;
199         }
200         if (sendData->responseInfo->isMulticast)
201         {
202             OIC_LOG(DEBUG, TAG, "multicast message can't be sent to the block");
203             return CA_NOT_SUPPORTED;
204         }
205     }
206
207     // #1. check if it is already included in block data list
208     CABlockData_t *currData = NULL;
209     CAResult_t res = CACheckBlockDataValidation(sendData, &currData);
210     if (CA_STATUS_OK != res)
211     {
212         // #2. if it is not included, add the data into list
213         if (!currData)
214         {
215             OIC_LOG(DEBUG, TAG, "There is no block data");
216
217             bool isBlock = CACheckPayloadLength(sendData);
218             if (!isBlock)
219             {
220                 if (sendData->requestInfo)
221                 {
222                     currData = CACreateNewBlockData(sendData);
223                     if (!currData)
224                     {
225                         OIC_LOG(ERROR, TAG, "failed to create block data");
226                         return CA_MEMORY_ALLOC_FAILED;
227                     }
228                 }
229                 return CA_NOT_SUPPORTED;
230             }
231             currData = CACreateNewBlockData(sendData);
232             if (!currData)
233             {
234                 OIC_LOG(ERROR, TAG, "failed to create block data");
235                 return CA_MEMORY_ALLOC_FAILED;
236             }
237         }
238     }
239
240     // #3. check request/response block option type and payload length
241     res = CACheckBlockOptionType(currData);
242     if (CA_STATUS_OK == res)
243     {
244         // #4. send block message
245         OIC_LOG(DEBUG, TAG, "send first block msg");
246         res = CAAddSendThreadQueue(currData->sentData,
247                                    (const CABlockDataID_t *) &currData->blockDataId);
248         if (CA_STATUS_OK != res)
249         {
250             OIC_LOG(ERROR, TAG, "add has failed");
251             return res;
252         }
253     }
254
255     return res;
256 }
257
258 CAResult_t CAAddSendThreadQueue(const CAData_t *sendData, const CABlockDataID_t *blockID)
259 {
260     VERIFY_NON_NULL(sendData, TAG, "sendData");
261     VERIFY_NON_NULL(blockID, TAG, "blockID");
262
263     CAData_t *cloneData = CACloneCAData(sendData);
264     if (!cloneData)
265     {
266         OIC_LOG(ERROR, TAG, "clone has failed");
267         CARemoveBlockDataFromList(blockID);
268         return CA_STATUS_FAILED;
269     }
270
271     if (g_context.sendThreadFunc)
272     {
273         oc_mutex_lock(g_context.blockDataSenderMutex);
274         g_context.sendThreadFunc(cloneData);
275         oc_mutex_unlock(g_context.blockDataSenderMutex);
276     }
277     else
278     {
279         CADestroyDataSet(cloneData);
280     }
281     return CA_STATUS_OK;
282 }
283
284 CAResult_t CACheckBlockOptionType(CABlockData_t *currData)
285 {
286     VERIFY_NON_NULL(currData, TAG, "currData");
287     VERIFY_NON_NULL(currData->sentData, TAG, "currData->sentData");
288
289     bool isBlock = CACheckPayloadLength(currData->sentData);
290     if (!isBlock)
291     {
292         return CA_NOT_SUPPORTED;
293     }
294
295     // set block option (COAP_OPTION_BLOCK2 or COAP_OPTION_BLOCK1)
296     if (currData->sentData->requestInfo) // request message
297     {
298         currData->type = COAP_OPTION_BLOCK1;
299     }
300     else // response message
301     {
302         currData->type = COAP_OPTION_BLOCK2;
303     }
304
305     return CA_STATUS_OK;
306 }
307
308 // TODO make pdu const after libcoap is updated to support that.
309 CAResult_t CAReceiveBlockWiseData(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
310                                   const CAData_t *receivedData, size_t dataLen)
311 {
312     OIC_LOG(DEBUG, TAG, "CAReceiveBlockWiseData");
313     VERIFY_NON_NULL(pdu, TAG, "pdu");
314     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
315     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
316     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
317
318     // check if received message type is CA_MSG_RESET
319     if (CA_EMPTY == pdu->transport_hdr->udp.code)
320     {
321         OIC_LOG(DEBUG, TAG, "code is CA_EMPTY..");
322
323         if (!receivedData->responseInfo->info.token)
324         {
325             // get token from block-wise transfer list when CA_EMPTY(RST/ACK) is received
326             CAResult_t res = CAGetTokenFromBlockDataList(pdu, endpoint,
327                                                          receivedData->responseInfo);
328             if (CA_STATUS_OK != res)
329             {
330                 OIC_LOG(ERROR, TAG, "fail to get token");
331                 return res;
332             }
333         }
334
335         CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
336                 receivedData->responseInfo->info.token,
337                 receivedData->responseInfo->info.tokenLength,
338                 endpoint->port);
339         if (NULL == blockDataID || blockDataID->idLength < 1)
340         {
341             // if retransmission is timeout, callback msg will be send without token.
342             if (NULL == blockDataID && !receivedData->responseInfo->info.token)
343             {
344                 OIC_LOG(INFO, TAG, "retransmission was stopped");
345                 return CA_REQUEST_TIMEOUT;
346             }
347
348             OIC_LOG(ERROR, TAG, "blockId is null");
349             CADestroyBlockID(blockDataID);
350             return CA_STATUS_FAILED;
351         }
352
353         // If we didn't send the last block message and received EMPTY message,
354         // we have to remain the block data from list.
355         CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
356         if (data && (data->block1.m || data->block2.m))
357         {
358             OIC_LOG(DEBUG, TAG, "this is normal EMPTY message for blockwise-transfer.");
359             CADestroyBlockID(blockDataID);
360             return CA_STATUS_OK;
361         }
362
363         CARemoveBlockDataFromList(blockDataID);
364         CADestroyBlockID(blockDataID);
365         return CA_NOT_SUPPORTED;
366     }
367
368     // check if block option is set and get block data
369     coap_block_t block = { 0, 0, 0 };
370
371     // get block1 option
372     int isBlock1 = coap_get_block(pdu, COAP_OPTION_BLOCK1, &block);
373     if (isBlock1)
374     {
375         CAResult_t res = CASetNextBlockOption1(pdu, endpoint, receivedData, block, dataLen);
376         if (CA_STATUS_OK != res)
377         {
378             OIC_LOG(ERROR, TAG, "setting has failed");
379             return res;
380         }
381     }
382
383     // get block2 option
384     int isBlock2 = coap_get_block(pdu, COAP_OPTION_BLOCK2, &block);
385     if (isBlock2)
386     {
387         CAResult_t res = CASetNextBlockOption2(pdu, endpoint, receivedData, block, dataLen);
388         if (CA_STATUS_OK != res)
389         {
390             OIC_LOG(ERROR, TAG, "setting has failed");
391             return res;
392         }
393     }
394
395     // if there is no block option in pdu, check if there is error code.
396     if (!isBlock1 && !isBlock2)
397     {
398         CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
399                 (CAToken_t)pdu->transport_hdr->udp.token,
400                 pdu->transport_hdr->udp.token_length,
401                 endpoint->port);
402         if (NULL == blockDataID || blockDataID->idLength < 1)
403         {
404             OIC_LOG(ERROR, TAG, "blockId is null");
405             CADestroyBlockID(blockDataID);
406             return CA_STATUS_FAILED;
407         }
408
409         uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
410         if (CA_REQUEST_ENTITY_INCOMPLETE == code)
411         {
412             CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
413             if (!data)
414             {
415                 OIC_LOG(ERROR, TAG, "getting has failed");
416                 CADestroyBlockID(blockDataID);
417                 return CA_STATUS_FAILED;
418             }
419
420             coap_block_t *block = CAGetBlockOption(blockDataID, data->type);
421             if (!block)
422             {
423                 OIC_LOG(ERROR, TAG, "block is null");
424                 CADestroyBlockID(blockDataID);
425                 return CA_STATUS_FAILED;
426             }
427
428             CAResult_t res = CA_STATUS_OK;
429             if (COAP_OPTION_BLOCK2 == data->type)
430             {
431                 res = CASetNextBlockOption2(pdu, endpoint, receivedData, *block, dataLen);
432                 if (CA_STATUS_OK != res)
433                 {
434                     OIC_LOG(ERROR, TAG, "setting has failed");
435                     CADestroyBlockID(blockDataID);
436                     return CA_STATUS_FAILED;
437                 }
438             }
439             else if (COAP_OPTION_BLOCK1 == data->type)
440             {
441                 res = CASetNextBlockOption1(pdu, endpoint, receivedData, *block, dataLen);
442                 if (CA_STATUS_OK != res)
443                 {
444                     OIC_LOG(ERROR, TAG, "setting has failed");
445                     CADestroyBlockID(blockDataID);
446                     return res;
447                 }
448             }
449             CADestroyBlockID(blockDataID);
450         }
451         else
452         {
453             // normal pdu data
454             OIC_LOG(DEBUG, TAG, "it's normal pdu");
455
456             // if received data is response message
457             // and sent data remain in block data list, remove block data
458             if (receivedData->responseInfo)
459             {
460                 CARemoveBlockDataFromList(blockDataID);
461             }
462             CADestroyBlockID(blockDataID);
463             return CA_NOT_SUPPORTED;
464         }
465     }
466     return CA_STATUS_OK;
467 }
468
469 CAResult_t CAProcessNextStep(const coap_pdu_t *pdu, const CAData_t *receivedData,
470                              uint8_t blockWiseStatus, const CABlockDataID_t *blockID)
471 {
472     VERIFY_NON_NULL(pdu, TAG, "pdu");
473     VERIFY_NON_NULL(pdu->hdr, TAG, "pdu->hdr");
474     VERIFY_NON_NULL(blockID, TAG, "blockID");
475
476     CAResult_t res = CA_STATUS_OK;
477     CAData_t *data = NULL;
478
479     // process blockWiseStatus
480     switch (blockWiseStatus)
481     {
482         case CA_OPTION2_FIRST_BLOCK:
483             res = CAAddSendThreadQueue(receivedData, blockID);
484             if (CA_STATUS_OK != res)
485             {
486                 OIC_LOG(ERROR, TAG, "add has failed");
487                 return res;
488             }
489             break;
490
491         case CA_OPTION2_REQUEST:
492             // add data to send thread
493             data = CAGetDataSetFromBlockDataList(blockID);
494             if (!data)
495             {
496                 OIC_LOG(ERROR, TAG, "it's unavailable");
497                 return CA_STATUS_FAILED;
498             }
499
500             if (data->responseInfo)
501             {
502                 data->responseInfo->info.type =
503                         (pdu->transport_hdr->udp.type == CA_MSG_CONFIRM) ?
504                                 CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM;
505                 data->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
506
507                 res = CAAddSendThreadQueue(data, blockID);
508                 if (CA_STATUS_OK != res)
509                 {
510                     OIC_LOG(ERROR, TAG, "add has failed");
511                     return res;
512                 }
513             }
514             break;
515
516         case CA_OPTION1_RESPONSE:
517         case CA_OPTION2_RESPONSE:
518         case CA_OPTION1_REQUEST_BLOCK:
519             res = CASendBlockMessage(pdu, pdu->transport_hdr->udp.type, blockID);
520             if (CA_STATUS_OK != res)
521             {
522                 OIC_LOG(ERROR, TAG, "send has failed");
523                 return res;
524             }
525             break;
526
527         case CA_OPTION2_LAST_BLOCK:
528             // process last block and send upper layer
529             res = CAReceiveLastBlock(blockID, receivedData);
530             if (CA_STATUS_OK != res)
531             {
532                 OIC_LOG(ERROR, TAG, "receive has failed");
533                 return res;
534             }
535
536             // remove data from list
537             res = CARemoveBlockDataFromList(blockID);
538             if (CA_STATUS_OK != res)
539             {
540                 OIC_LOG(ERROR, TAG, "remove has failed");
541                 return res;
542             }
543             break;
544
545         case CA_OPTION1_REQUEST_LAST_BLOCK:
546             // process last block and send upper layer
547             res = CAReceiveLastBlock(blockID, receivedData);
548             if (CA_STATUS_OK != res)
549             {
550                 OIC_LOG(ERROR, TAG, "receive has failed");
551                 return res;
552             }
553             break;
554
555         case CA_BLOCK_INCOMPLETE:
556             // add data to send thread
557             res = CASendErrorMessage(pdu, blockWiseStatus, CA_REQUEST_ENTITY_INCOMPLETE, blockID);
558             if (CA_STATUS_OK != res)
559             {
560                 OIC_LOG(ERROR, TAG, "send has failed");
561                 return res;
562             }
563             break;
564
565         case CA_BLOCK_TOO_LARGE:
566             if (receivedData->requestInfo)
567             {
568                 res = CASendErrorMessage(pdu, blockWiseStatus, CA_REQUEST_ENTITY_TOO_LARGE,
569                                          blockID);
570                 if (CA_STATUS_OK != res)
571                 {
572                     OIC_LOG(ERROR, TAG, "send has failed");
573                     return res;
574                 }
575             }
576             else if (receivedData->responseInfo)
577             {
578                 res = CASendBlockMessage(pdu, pdu->transport_hdr->udp.type, blockID);
579                 if (CA_STATUS_OK != res)
580                 {
581                     OIC_LOG(ERROR, TAG, "send has failed");
582                     return res;
583                 }
584             }
585             break;
586         default:
587             OIC_LOG_V(ERROR, TAG, "no logic [%d]", blockWiseStatus);
588     }
589     return CA_STATUS_OK;
590 }
591
592 static CAResult_t CASendDirectEmptyResponse(const CAEndpoint_t *endpoint, uint16_t messageId)
593 {
594     OIC_LOG(DEBUG, TAG, "Entering CASendDirectEmptyResponse");
595     CAResponseInfo_t respInfo = {
596         .result = CA_EMPTY
597     };
598     respInfo.info.type = CA_MSG_ACKNOWLEDGE;
599     respInfo.info.messageId = messageId;
600     respInfo.info.dataType = CA_RESPONSE_DATA;
601
602     CAResult_t caResult = CASendResponse(endpoint, &respInfo);
603
604     OIC_LOG(DEBUG, TAG, "Exit CASendDirectEmptyResponse");
605     return caResult;
606 }
607
608 CAResult_t CASendBlockMessage(const coap_pdu_t *pdu, CAMessageType_t msgType,
609                               const CABlockDataID_t *blockID)
610 {
611     VERIFY_NON_NULL(pdu, TAG, "pdu");
612     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
613     VERIFY_NON_NULL(blockID, TAG, "blockID");
614
615     CAData_t *data = CAGetDataSetFromBlockDataList(blockID);
616     if (!data)
617     {
618         OIC_LOG(ERROR, TAG, "CAData is unavailable");
619         return CA_STATUS_FAILED;
620     }
621
622     CAMessageType_t sentMsgType = CA_MSG_NONCONFIRM;
623     switch (msgType)
624     {
625         case CA_MSG_CONFIRM:
626             sentMsgType = CA_MSG_ACKNOWLEDGE;
627             break;
628         case CA_MSG_ACKNOWLEDGE:
629             sentMsgType = CA_MSG_CONFIRM;
630             break;
631         default:
632             sentMsgType = CA_MSG_NONCONFIRM;
633             break;
634     }
635
636     uint32_t code = pdu->transport_hdr->udp.code;
637     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
638     {
639         if (data->responseInfo)
640         {
641             OIC_LOG(DEBUG, TAG, "set response info");
642             data->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
643             data->responseInfo->info.type = sentMsgType;
644             data->responseInfo->result = CA_CONTINUE;
645         }
646     }
647     else
648     {
649         if (data->requestInfo)
650         {
651             // if the received response message type is CON, send empty message.
652             // and then, send next block request message with new messagId.
653             if (msgType == CA_MSG_CONFIRM)
654             {
655                 CASendDirectEmptyResponse(data->remoteEndpoint,
656                                           data->requestInfo->info.messageId);
657                 sentMsgType = CA_MSG_CONFIRM;
658             }
659
660             OIC_LOG(DEBUG, TAG, "need new msgID");
661             data->requestInfo->info.messageId = 0;
662             data->requestInfo->info.type = sentMsgType;
663         }
664         else if (data->responseInfo)
665         {
666             data->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
667             data->responseInfo->info.type = sentMsgType;
668         }
669     }
670
671     // add data to send thread
672     CAResult_t res = CAAddSendThreadQueue(data, blockID);
673     if (CA_STATUS_OK != res)
674     {
675         OIC_LOG(ERROR, TAG, "add has failed");
676     }
677
678     return res;
679 }
680
681 CAResult_t CASendErrorMessage(const coap_pdu_t *pdu, uint8_t status,
682                               CAResponseResult_t responseResult, const CABlockDataID_t *blockID)
683 {
684     VERIFY_NON_NULL(pdu, TAG, "pdu");
685     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
686     VERIFY_NON_NULL(blockID, TAG, "blockID");
687
688     // create error responseInfo
689     CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockID);
690     if (!data)
691     {
692         OIC_LOG(ERROR, TAG, "data is unavailable");
693         return CA_STATUS_FAILED;
694     }
695
696     if (!data->sentData)
697     {
698         OIC_LOG(ERROR, TAG, "data has no sent-data");
699         return CA_STATUS_FAILED;
700     }
701
702     CAData_t *cloneData = CACloneCAData(data->sentData);
703     if (!cloneData)
704     {
705         OIC_LOG(ERROR, TAG, "clone has failed");
706         return CA_MEMORY_ALLOC_FAILED;
707     }
708
709     CAMessageType_t sentMsgType = CA_MSG_NONCONFIRM;
710     switch (pdu->transport_hdr->udp.type)
711     {
712         case CA_MSG_CONFIRM:
713             sentMsgType = CA_MSG_ACKNOWLEDGE;
714             break;
715         case CA_MSG_ACKNOWLEDGE:
716             sentMsgType = CA_MSG_CONFIRM;
717             break;
718         default:
719             sentMsgType = CA_MSG_NONCONFIRM;
720     }
721
722     if (cloneData->responseInfo)
723     {
724         cloneData->responseInfo->info.messageId = pdu->transport_hdr->udp.id;
725         cloneData->responseInfo->info.type = sentMsgType;
726         cloneData->responseInfo->result = responseResult;
727     }
728     else
729     {
730         CAInfo_t responseData = { .tokenLength = pdu->transport_hdr->udp.token_length };
731         responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
732         if (!responseData.token)
733         {
734             OIC_LOG(ERROR, TAG, "out of memory");
735             CADestroyDataSet(cloneData);
736             return CA_MEMORY_ALLOC_FAILED;
737         }
738         memcpy(responseData.token, pdu->transport_hdr->udp.token, responseData.tokenLength);
739
740         cloneData->responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
741         if (!cloneData->responseInfo)
742         {
743             OIC_LOG(ERROR, TAG, "out of memory");
744             CADestroyDataSet(cloneData);
745             OICFree(responseData.token);
746             return CA_MEMORY_ALLOC_FAILED;
747         }
748
749         cloneData->responseInfo->info = responseData;
750         cloneData->responseInfo->info.type = sentMsgType;
751         cloneData->responseInfo->result = responseResult;
752     }
753
754     OIC_LOG(DEBUG, TAG, "set response message to send error code");
755
756     // if there is a requestInfo, remove it to send response message
757     if (cloneData->requestInfo)
758     {
759         CADestroyRequestInfoInternal(cloneData->requestInfo);
760         cloneData->requestInfo = NULL;
761     }
762
763     // add data to send thread
764     if (g_context.sendThreadFunc)
765     {
766         oc_mutex_lock(g_context.blockDataSenderMutex);
767         g_context.sendThreadFunc(cloneData);
768         oc_mutex_unlock(g_context.blockDataSenderMutex);
769     }
770     else
771     {
772         CADestroyDataSet(cloneData);
773     }
774
775     // if error code is 4.08, remove the stored payload and initialize block number
776     if (CA_BLOCK_INCOMPLETE == status)
777     {
778         OICFree(data->payload);
779         data->payload = NULL;
780         data->payloadLength = 0;
781         data->receivedPayloadLen = 0;
782         data->block1.num = 0;
783         data->block2.num = 0;
784     }
785
786     return CA_STATUS_OK;
787 }
788
789 CAResult_t CAReceiveLastBlock(const CABlockDataID_t *blockID, const CAData_t *receivedData)
790 {
791     VERIFY_NON_NULL(blockID, TAG, "blockID");
792     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
793
794     // total block data have to notify to Application
795     CAData_t *cloneData = CACloneCAData(receivedData);
796     if (!cloneData)
797     {
798         OIC_LOG(ERROR, TAG, "clone has failed");
799         return CA_MEMORY_ALLOC_FAILED;
800     }
801
802     // update payload
803     size_t fullPayloadLen = 0;
804     CAPayload_t fullPayload = CAGetPayloadFromBlockDataList(blockID, &fullPayloadLen);
805     if (fullPayload)
806     {
807         CAResult_t res = CAUpdatePayloadToCAData(cloneData, fullPayload, fullPayloadLen);
808         if (CA_STATUS_OK != res)
809         {
810             OIC_LOG(ERROR, TAG, "update has failed");
811             CADestroyDataSet(cloneData);
812             return res;
813         }
814     }
815
816     if (g_context.receivedThreadFunc)
817     {
818         g_context.receivedThreadFunc(cloneData);
819     }
820     else
821     {
822         CADestroyDataSet(cloneData);
823     }
824
825     return CA_STATUS_OK;
826 }
827
828 static CABlockData_t* CACheckTheExistOfBlockData(const CABlockDataID_t* blockDataID,
829                                                  coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
830                                                  uint8_t blockType)
831 {
832     // Get BlockData data. If does not exist, create a new data
833     CABlockData_t *data = CAGetBlockDataFromBlockDataList(blockDataID);
834     if (!data)
835     {
836         OIC_LOG(DEBUG, TAG, "block data doesn't exist in list. create new one");
837
838         CAData_t *cadata = CACreateNewDataSet(pdu, endpoint);
839         if (!cadata)
840         {
841             OIC_LOG(ERROR, TAG, "data is null");
842             return NULL;
843         }
844
845         data = CACreateNewBlockData(cadata);
846         if (!data)
847         {
848             OIC_LOG(ERROR, TAG, "failed to create a new block data");
849             CADestroyDataSet(cadata);
850             return NULL;
851         }
852         CADestroyDataSet(cadata);
853     }
854
855     // update BLOCK OPTION type
856     CAResult_t res = CAUpdateBlockOptionType(blockDataID, blockType);
857     if (CA_STATUS_OK != res)
858     {
859         OIC_LOG(ERROR, TAG, "update has failed");
860         return NULL;
861     }
862
863     return data;
864 }
865
866 // TODO make pdu const after libcoap is updated to support that.
867 CAResult_t CASetNextBlockOption1(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
868                                  const CAData_t *receivedData, coap_block_t block,
869                                  size_t dataLen)
870 {
871     OIC_LOG(INFO, TAG, "CASetNextBlockOption1");
872     VERIFY_NON_NULL(pdu, TAG, "pdu");
873     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
874     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
875     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
876
877     OIC_LOG_V(INFO, TAG, "num:%d, M:%d, sze:%d", block.num, block.m, block.szx);
878
879     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
880             (CAToken_t)pdu->transport_hdr->udp.token,
881             pdu->transport_hdr->udp.token_length,
882             endpoint->port);
883     if (NULL == blockDataID || blockDataID->idLength < 1)
884     {
885         OIC_LOG(ERROR, TAG, "blockId is null");
886         CADestroyBlockID(blockDataID);
887         return CA_STATUS_FAILED;
888     }
889
890     CAResult_t res = CA_STATUS_OK;
891     CABlockData_t *data = CACheckTheExistOfBlockData(blockDataID, pdu, endpoint,
892                                                      COAP_OPTION_BLOCK1);
893     if (!data)
894     {
895         OIC_LOG(ERROR, TAG, "Failed to create or get block data");
896         res = CA_STATUS_FAILED;
897         goto exit;
898     }
899
900     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
901     uint32_t code = pdu->transport_hdr->udp.code;
902     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
903     {
904         // received message type is request
905         OIC_LOG_V(INFO, TAG, "num:%d, M:%d", block.num, block.m);
906
907         // check the size option
908         bool isSizeOption = CAIsPayloadLengthInPduWithBlockSizeOption(pdu, COAP_OPTION_SIZE1,
909                                                                       &(data->payloadLength));
910
911         blockWiseStatus = CACheckBlockErrorType(data, &block, receivedData,
912                                                 COAP_OPTION_BLOCK1, dataLen);
913
914         if (CA_BLOCK_RECEIVED_ALREADY != blockWiseStatus)
915         {
916             // store the received payload and merge
917             res = CAUpdatePayloadData(data, receivedData, blockWiseStatus,
918                                       isSizeOption, COAP_OPTION_BLOCK1);
919             if (CA_STATUS_OK != res)
920             {
921                 OIC_LOG(ERROR, TAG, "update has failed");
922                 goto exit;
923             }
924
925             res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK1,
926                                            blockWiseStatus);
927             if (CA_STATUS_OK != res)
928             {
929                 OIC_LOG(ERROR, TAG, "update has failed");
930                 goto exit;
931             }
932
933             // update block data
934             res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK1);
935             if (CA_STATUS_OK != res)
936             {
937                 OIC_LOG(ERROR, TAG, "update has failed");
938                 goto exit;
939             }
940         }
941
942         // check the blcok-wise transfer status for next step
943         if (CA_BLOCK_UNKNOWN == blockWiseStatus || CA_BLOCK_RECEIVED_ALREADY == blockWiseStatus)
944         {
945             OIC_LOG_V(DEBUG, TAG, "M bit is %d", block.m);
946
947             blockWiseStatus = (0 == block.m) ?
948                     CA_OPTION1_REQUEST_LAST_BLOCK : CA_OPTION1_REQUEST_BLOCK;
949         }
950     }
951     else
952     {
953         // received message type is response
954         uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
955         if (0 == block.m && (CA_REQUEST_ENTITY_INCOMPLETE != code
956                 && CA_REQUEST_ENTITY_TOO_LARGE != code))
957         {
958             int isBlock2 = coap_get_block(pdu, COAP_OPTION_BLOCK2, &block);
959             if (isBlock2)
960             {
961                 OIC_LOG(INFO, TAG, "received data is combining block1 and block2");
962                 // initialize block number for response message
963                 data->block1.num = 0;
964                 CADestroyBlockID(blockDataID);
965                 return CA_STATUS_OK;
966             }
967             else
968             {
969                 OIC_LOG(INFO, TAG, "received data is not bulk data");
970                 CAReceiveLastBlock(blockDataID, receivedData);
971                 res = CA_STATUS_OK;
972                 goto exit;
973             }
974         }
975
976         blockWiseStatus = CA_OPTION1_RESPONSE;
977         res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK1, blockWiseStatus);
978         if (CA_STATUS_OK != res)
979         {
980             OIC_LOG(ERROR, TAG, "update has failed");
981             CADestroyBlockID(blockDataID);
982             return res;
983         }
984
985         res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK1);
986         if (CA_STATUS_OK != res)
987         {
988             OIC_LOG(ERROR, TAG, "update has failed");
989             goto exit;
990         }
991     }
992
993     res = CAProcessNextStep(pdu, receivedData, blockWiseStatus, blockDataID);
994     if (CA_STATUS_OK != res)
995     {
996         OIC_LOG(ERROR, TAG, "setting has failed");
997         goto exit;
998     }
999
1000     CADestroyBlockID(blockDataID);
1001     return res;
1002
1003 exit:
1004     CARemoveBlockDataFromList(blockDataID);
1005     CADestroyBlockID(blockDataID);
1006     return res;
1007 }
1008
1009 // TODO make pdu const after libcoap is updated to support that.
1010 CAResult_t CASetNextBlockOption2(coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
1011                                  const CAData_t *receivedData, coap_block_t block,
1012                                  size_t dataLen)
1013 {
1014     OIC_LOG(DEBUG, TAG, "CASetNextBlockOption2");
1015     OIC_LOG_V(INFO, TAG, "num:%d, M:%d, sze:%d", block.num, block.m, block.szx);
1016
1017     VERIFY_NON_NULL(pdu, TAG, "pdu");
1018     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
1019     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1020     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
1021
1022     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
1023             (CAToken_t)pdu->transport_hdr->udp.token,
1024             pdu->transport_hdr->udp.token_length,
1025             endpoint->port);
1026     if (NULL == blockDataID || blockDataID->idLength < 1)
1027     {
1028         OIC_LOG(ERROR, TAG, "blockId is null");
1029         CADestroyBlockID(blockDataID);
1030         return CA_STATUS_FAILED;
1031     }
1032
1033     CAResult_t res = CA_STATUS_OK;
1034     CABlockData_t *data = CACheckTheExistOfBlockData(blockDataID, pdu, endpoint,
1035                                                      COAP_OPTION_BLOCK2);
1036     if (!data)
1037     {
1038         OIC_LOG(ERROR, TAG, "Failed to create or get block data");
1039         res = CA_STATUS_FAILED;
1040         goto exit;
1041     }
1042
1043     uint8_t blockWiseStatus = CA_BLOCK_UNKNOWN;
1044     if (0 == block.num && CA_GET == pdu->transport_hdr->udp.code && 0 == block.m)
1045     {
1046         OIC_LOG(INFO, TAG, "first block number");
1047
1048         res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK2, blockWiseStatus);
1049         if (CA_STATUS_OK != res)
1050         {
1051             OIC_LOG(ERROR, TAG, "update has failed");
1052             goto exit;
1053         }
1054
1055         // first block data have to notify to Application
1056         res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK2);
1057         if (CA_STATUS_OK != res)
1058         {
1059             OIC_LOG(ERROR, TAG, "update has failed");
1060             goto exit;
1061         }
1062         blockWiseStatus = CA_OPTION2_FIRST_BLOCK;
1063     }
1064     else
1065     {
1066         uint32_t code = pdu->transport_hdr->udp.code;
1067         if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
1068         {
1069             // received message type is request
1070             OIC_LOG_V(INFO, TAG, "num:%d, M:%d", block.num, block.m);
1071
1072             blockWiseStatus = CA_OPTION2_REQUEST;
1073
1074             res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK2, blockWiseStatus);
1075             if (CA_STATUS_OK != res)
1076             {
1077                 OIC_LOG(ERROR, TAG, "update has failed");
1078                 goto exit;
1079             }
1080
1081             res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK2);
1082             if (CA_STATUS_OK != res)
1083             {
1084                 OIC_LOG(ERROR, TAG, "update has failed");
1085                 goto exit;
1086             }
1087         }
1088         else
1089         {
1090             // received message type is response
1091             OIC_LOG(DEBUG, TAG, "received response message with block option2");
1092
1093             // check the size option
1094             bool isSizeOption = CAIsPayloadLengthInPduWithBlockSizeOption(pdu,
1095                                                                           COAP_OPTION_SIZE2,
1096                                                                           &(data->payloadLength));
1097
1098             uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
1099             if (CA_REQUEST_ENTITY_INCOMPLETE != code && CA_REQUEST_ENTITY_TOO_LARGE != code)
1100             {
1101                 // check if received payload is exact
1102                 blockWiseStatus = CACheckBlockErrorType(data, &block, receivedData,
1103                                                         COAP_OPTION_BLOCK2, dataLen);
1104             }
1105
1106             if (CA_BLOCK_RECEIVED_ALREADY != blockWiseStatus)
1107             {
1108                 // store the received payload and merge
1109                 res = CAUpdatePayloadData(data, receivedData, blockWiseStatus,
1110                                           isSizeOption, COAP_OPTION_BLOCK2);
1111                 if (CA_STATUS_OK != res)
1112                 {
1113                     OIC_LOG(ERROR, TAG, "update has failed");
1114                     goto exit;
1115                 }
1116             }
1117
1118             if (0 == block.m && CA_BLOCK_UNKNOWN == blockWiseStatus) // Last block is received
1119             {
1120                 OIC_LOG(DEBUG, TAG, "M bit is 0");
1121                 blockWiseStatus = CA_OPTION2_LAST_BLOCK;
1122             }
1123             else
1124             {
1125                 if (CA_BLOCK_UNKNOWN == blockWiseStatus ||
1126                         CA_BLOCK_RECEIVED_ALREADY == blockWiseStatus)
1127                 {
1128                     OIC_LOG(DEBUG, TAG, "M bit is 1");
1129                     blockWiseStatus = CA_OPTION2_RESPONSE;
1130                 }
1131
1132                 res = CAUpdateBlockOptionItems(data, pdu, &block, COAP_OPTION_BLOCK2,
1133                                                blockWiseStatus);
1134                 if (CA_STATUS_OK != res)
1135                 {
1136                     OIC_LOG(ERROR, TAG, "update has failed");
1137                     goto exit;
1138                 }
1139
1140                 res = CAUpdateBlockData(data, block, COAP_OPTION_BLOCK2);
1141                 if (CA_STATUS_OK != res)
1142                 {
1143                     OIC_LOG(ERROR, TAG, "update has failed");
1144                     goto exit;
1145                 }
1146             }
1147         }
1148     }
1149
1150     res = CAProcessNextStep(pdu, receivedData, blockWiseStatus, blockDataID);
1151     if (CA_STATUS_OK != res)
1152     {
1153         OIC_LOG(ERROR, TAG, "setting has failed");
1154         goto exit;
1155     }
1156
1157     CADestroyBlockID(blockDataID);
1158     return CA_STATUS_OK;
1159
1160 exit:
1161     CARemoveBlockDataFromList(blockDataID);
1162     CADestroyBlockID(blockDataID);
1163     return res;
1164 }
1165
1166 CAResult_t CAUpdateBlockOptionItems(CABlockData_t *currData, const coap_pdu_t *pdu,
1167                                     coap_block_t *block, uint16_t blockType,
1168                                     uint32_t status)
1169 {
1170     VERIFY_NON_NULL(currData, TAG, "currData");
1171     VERIFY_NON_NULL(pdu, TAG, "pdu");
1172     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
1173     VERIFY_NON_NULL(block, TAG, "block");
1174
1175     // update block data
1176     CAResult_t res = CA_STATUS_OK;
1177     uint32_t code = CA_RESPONSE_CODE(pdu->transport_hdr->udp.code);
1178
1179     if (CA_REQUEST_ENTITY_INCOMPLETE == code || CA_REQUEST_ENTITY_TOO_LARGE == code)
1180     {
1181         // response error code of the received block message
1182         res = CAHandleBlockErrorResponse(block, blockType, code);
1183         if (CA_STATUS_OK != res)
1184         {
1185             OIC_LOG(ERROR, TAG, "error handle has failed");
1186             return res;
1187         }
1188     }
1189     else
1190     {
1191         // update block option items
1192         switch (status)
1193         {
1194             case CA_OPTION1_RESPONSE:
1195                 if (currData->block1.num > block->num)
1196                 {
1197                     OIC_LOG(ERROR, TAG, "received incorrect block num");
1198                     return CA_STATUS_FAILED;
1199                 }
1200                 block->num++;
1201                 break;
1202             case CA_OPTION2_REQUEST:
1203                 block->m = 0;
1204                 break;
1205             case CA_OPTION2_RESPONSE:
1206                 if (currData->block2.num > block->num)
1207                 {
1208                     OIC_LOG(ERROR, TAG, "received incorrect block num");
1209                     return CA_STATUS_FAILED;
1210                 }
1211                 block->num++;
1212                 block->m = 0;
1213                 break;
1214             case CA_BLOCK_TOO_LARGE:
1215                 // if state of received block message is CA_BLOCK_TOO_LARGE or CA_BLOCK_INCOMPLETE
1216                 // we set the response error code appropriately and send
1217                 if (COAP_OPTION_BLOCK2 == blockType)
1218                 {
1219                     block->num++;
1220                     block->m = 0;
1221                     block->szx = currData->block2.szx;
1222                 }
1223                 else
1224                 {
1225                     block->szx = currData->block1.szx;
1226                 }
1227                 break;
1228             default:
1229                 OIC_LOG_V(ERROR, TAG, "no logic [%d]", status);
1230         }
1231
1232         if (CA_BLOCK_INCOMPLETE != status && CA_BLOCK_TOO_LARGE != status)
1233         {
1234             // negotiate block size
1235             res = CANegotiateBlockSize(currData, block, pdu, blockType);
1236             if (CA_STATUS_OK != res)
1237             {
1238                 OIC_LOG(ERROR, TAG, "negotiation has failed");
1239                 return res;
1240             }
1241         }
1242     }
1243     return res;
1244 }
1245
1246 CAResult_t CASetMoreBitFromBlock(size_t payloadLen, coap_block_t *block)
1247 {
1248     VERIFY_NON_NULL(block, TAG, "block");
1249
1250     if ((size_t) ((block->num + 1) << (block->szx + BLOCK_NUMBER_IDX)) < payloadLen)
1251     {
1252         OIC_LOG(DEBUG, TAG, "Set the M-bit(1)");
1253         block->m = 1;
1254     }
1255     else
1256     {
1257         OIC_LOG(DEBUG, TAG, "Set the M-bit(0)");
1258         block->m = 0;
1259     }
1260
1261     return CA_STATUS_OK;
1262 }
1263
1264 CAResult_t CANegotiateBlockSize(CABlockData_t *currData, coap_block_t *block,
1265                                 const coap_pdu_t *pdu, uint16_t blockType)
1266 {
1267     OIC_LOG(DEBUG, TAG, "IN-NegotiateBlockSize");
1268
1269     VERIFY_NON_NULL(currData, TAG, "currData");
1270     VERIFY_NON_NULL(block, TAG, "block");
1271     VERIFY_NON_NULL(pdu, TAG, "pdu");
1272     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
1273
1274     bool isReqMsg = false;
1275     uint32_t code = pdu->transport_hdr->udp.code;
1276     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
1277     {
1278         isReqMsg = true;
1279     }
1280
1281     // #1. check the block option type
1282     if (COAP_OPTION_BLOCK2 == blockType)
1283     {
1284         // #2. check the message type
1285         if (!isReqMsg)
1286         {
1287             if (block->szx > currData->block2.szx)
1288             {
1289                 OIC_LOG(DEBUG, TAG, "sze is big");
1290
1291                 // #3. calculate new block number from block size
1292                 unsigned int blockNum = BLOCK_SIZE(block->szx) /
1293                                         BLOCK_SIZE(currData->block2.szx) - 1;
1294                 OIC_LOG(DEBUG, TAG, "num is set as Negotiation");
1295                 block->num += blockNum;
1296                 block->szx = currData->block2.szx;
1297                 OIC_LOG_V(DEBUG, TAG, "updated block num: %d", block->num);
1298             }
1299         }
1300         else
1301         {
1302             if (block->szx > currData->block2.szx)
1303             {
1304                 OIC_LOG(DEBUG, TAG, "sze is big");
1305                 block->szx = currData->block2.szx;
1306             }
1307         }
1308     }
1309     else if (COAP_OPTION_BLOCK1 == blockType)
1310     {
1311         if (!isReqMsg)
1312         {
1313             if (block->szx < currData->block1.szx)
1314             {
1315                 OIC_LOG(DEBUG, TAG, "sze is small");
1316
1317                 unsigned int blockNum = BLOCK_SIZE(currData->block1.szx) /
1318                                         BLOCK_SIZE(block->szx) - 1;
1319                 block->num += blockNum;
1320                 OIC_LOG_V(DEBUG, TAG, "updated block num: %d", block->num);
1321             }
1322         }
1323         else
1324         {
1325             if (block->szx > currData->block1.szx)
1326             {
1327                 OIC_LOG(DEBUG, TAG, "sze is big");
1328                 block->szx = currData->block1.szx;
1329             }
1330         }
1331     }
1332     else
1333     {
1334         OIC_LOG(DEBUG, TAG, "Invalid block option");
1335         return CA_STATUS_FAILED;
1336     }
1337
1338     OIC_LOG(DEBUG, TAG, "OUT-NegotiateBlockSize");
1339
1340     return CA_STATUS_OK;
1341 }
1342
1343 CAResult_t CAUpdateBlockData(CABlockData_t *currData, coap_block_t block,
1344                              uint16_t blockType)
1345 {
1346     VERIFY_NON_NULL(currData, TAG, "currData");
1347
1348     // check if block size is bigger than CABlockSize_t
1349     if (block.szx > CA_BLOCK_SIZE_1024_BYTE)
1350     {
1351         OIC_LOG(DEBUG, TAG, "invalid block szx");
1352         return CA_STATUS_FAILED;
1353     }
1354
1355     // update block option
1356     if (COAP_OPTION_BLOCK2 == blockType)
1357     {
1358         currData->block2 = block;
1359     }
1360     else
1361     {
1362         currData->block1 = block;
1363     }
1364
1365     OIC_LOG(DEBUG, TAG, "data has updated");
1366     return CA_STATUS_OK;
1367 }
1368
1369 CAResult_t CAUpdateMessageId(coap_pdu_t *pdu, const CABlockDataID_t *blockID)
1370 {
1371     VERIFY_NON_NULL(pdu, TAG, "pdu");
1372     VERIFY_NON_NULL(pdu->transport_hdr, TAG, "pdu->transport_hdr");
1373     VERIFY_NON_NULL(blockID, TAG, "blockID");
1374
1375     // if message is sent, update messageId in block-wise transfer list
1376     CAData_t * cadata = CAGetDataSetFromBlockDataList(blockID);
1377     if (!cadata)
1378     {
1379         OIC_LOG(ERROR, TAG, "CAData is unavailable");
1380         return CA_STATUS_FAILED;
1381     }
1382
1383     if (cadata->requestInfo)
1384     {
1385         cadata->requestInfo->info.messageId = pdu->transport_hdr->udp.id;
1386     }
1387
1388     return CA_STATUS_OK;
1389 }
1390
1391 CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
1392                             const CAEndpoint_t *endpoint, coap_list_t **options)
1393 {
1394     OIC_LOG(DEBUG, TAG, "IN-AddBlockOption");
1395     VERIFY_NON_NULL(pdu, TAG, "pdu");
1396     VERIFY_NON_NULL((*pdu), TAG, "(*pdu)");
1397     VERIFY_NON_NULL((*pdu)->transport_hdr, TAG, "(*pdu)->transport_hdr");
1398     VERIFY_NON_NULL(info, TAG, "info");
1399     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
1400     VERIFY_NON_NULL(options, TAG, "options");
1401
1402     CAResult_t res = CA_STATUS_OK;
1403     size_t dataLength = 0;
1404     if (info->payload)
1405     {
1406         dataLength = info->payloadSize;
1407         OIC_LOG_V(DEBUG, TAG, "dataLength - %zu", dataLength);
1408     }
1409
1410     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
1411             (CAToken_t)(*pdu)->transport_hdr->udp.token,
1412             (*pdu)->transport_hdr->udp.token_length,
1413             endpoint->port);
1414     if (NULL == blockDataID || blockDataID->idLength < 1)
1415     {
1416         OIC_LOG(ERROR, TAG, "blockId is null");
1417         res = CA_STATUS_FAILED;
1418         goto exit;
1419     }
1420
1421     uint32_t repCode = CA_RESPONSE_CODE((*pdu)->transport_hdr->udp.code);
1422     if (CA_REQUEST_ENTITY_INCOMPLETE == repCode)
1423     {
1424         OIC_LOG(INFO, TAG, "don't use option");
1425         res = CA_STATUS_OK;
1426         goto exit;
1427     }
1428
1429     uint8_t blockType = CAGetBlockOptionType(blockDataID);
1430     if (COAP_OPTION_BLOCK2 == blockType)
1431     {
1432         res = CAAddBlockOption2(pdu, info, dataLength, blockDataID, options);
1433         if (CA_STATUS_OK != res)
1434         {
1435             OIC_LOG(ERROR, TAG, "add has failed");
1436             goto exit;
1437         }
1438     }
1439     else if (COAP_OPTION_BLOCK1 == blockType)
1440     {
1441         res = CAAddBlockOption1(pdu, info, dataLength, blockDataID, options);
1442         if (CA_STATUS_OK != res)
1443         {
1444             OIC_LOG(ERROR, TAG, "add has failed");
1445             goto exit;
1446         }
1447     }
1448     else
1449     {
1450         OIC_LOG(DEBUG, TAG, "no BLOCK option");
1451
1452         // in case it is not large data, add option list to pdu.
1453         if (*options)
1454         {
1455             for (coap_list_t *opt = *options; opt; opt = opt->next)
1456             {
1457                 OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
1458                           COAP_OPTION_DATA(*(coap_option *) opt->data));
1459                 OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", (*pdu)->length);
1460
1461                 if (0 == coap_add_option(*pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
1462                                          COAP_OPTION_LENGTH(*(coap_option *) opt->data),
1463                                          COAP_OPTION_DATA(*(coap_option *) opt->data)))
1464                 {
1465                     OIC_LOG(ERROR, TAG, "coap_add_option has failed");
1466                     res = CA_STATUS_FAILED;
1467                     goto exit;
1468                 }
1469             }
1470         }
1471         OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", (*pdu)->length);
1472
1473         // if response data is so large. it have to send as block transfer
1474         if (!coap_add_data(*pdu, dataLength, (const unsigned char *) info->payload))
1475         {
1476             OIC_LOG(INFO, TAG, "it has to use block");
1477             res = CA_STATUS_FAILED;
1478             goto exit;
1479         }
1480         else
1481         {
1482             OIC_LOG(INFO, TAG, "not Blockwise Transfer");
1483         }
1484     }
1485
1486     uint32_t code = (*pdu)->transport_hdr->udp.code;
1487     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
1488     {
1489         // if received message type is RESET from remote device,
1490         // we have to use the updated message id of request message to find token.
1491         CABlockData_t *blockData = CAGetBlockDataFromBlockDataList(blockDataID);
1492         if (blockData)
1493         {
1494             res = CAUpdateMessageId(*pdu, blockDataID);
1495             if (CA_STATUS_OK != res)
1496             {
1497                 OIC_LOG(ERROR, TAG, "fail to update message id");
1498                 goto exit;
1499             }
1500         }
1501     }
1502
1503     CAResetBlockDataTTL(blockDataID);
1504 exit:
1505     CADestroyBlockID(blockDataID);
1506     OIC_LOG(DEBUG, TAG, "OUT-AddBlockOption");
1507     return res;
1508 }
1509
1510 CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
1511                              const CABlockDataID_t *blockID, coap_list_t **options)
1512 {
1513     OIC_LOG(DEBUG, TAG, "IN-AddBlockOption2");
1514     VERIFY_NON_NULL(pdu, TAG, "pdu");
1515     VERIFY_NON_NULL((*pdu), TAG, "(*pdu)");
1516     VERIFY_NON_NULL((*pdu)->transport_hdr, TAG, "(*pdu)->transport_hdr");
1517     VERIFY_NON_NULL(info, TAG, "info");
1518     VERIFY_NON_NULL(blockID, TAG, "blockID");
1519     VERIFY_NON_NULL(options, TAG, "options");
1520
1521     // get set block data from CABlock list-set.
1522     coap_block_t *block1 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK1);
1523     coap_block_t *block2 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK2);
1524     if (!block1 || !block2)
1525     {
1526         OIC_LOG(ERROR, TAG, "getting has failed");
1527         return CA_STATUS_FAILED;
1528     }
1529
1530     CAResult_t res = CA_STATUS_OK;
1531     uint32_t code = (*pdu)->transport_hdr->udp.code;
1532     if (CA_GET != code && CA_POST != code && CA_PUT != code && CA_DELETE != code)
1533     {
1534         CASetMoreBitFromBlock(dataLength, block2);
1535
1536         // if block number is 0, add size2 option
1537         if (0 == block2->num)
1538         {
1539             res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
1540             if (CA_STATUS_OK != res)
1541             {
1542                 OIC_LOG(ERROR, TAG, "add has failed");
1543                 goto exit;
1544             }
1545         }
1546
1547         res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
1548         if (CA_STATUS_OK != res)
1549         {
1550             OIC_LOG(ERROR, TAG, "add has failed");
1551             goto exit;
1552         }
1553
1554         if (block1->num)
1555         {
1556             OIC_LOG(DEBUG, TAG, "combining block1 and block2");
1557             res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
1558             if (CA_STATUS_OK != res)
1559             {
1560                 OIC_LOG(ERROR, TAG, "add has failed");
1561                 goto exit;
1562             }
1563             // initialize block number
1564             block1->num = 0;
1565         }
1566
1567         res = CAAddOptionToPDU(*pdu, options);
1568         if (CA_STATUS_OK != res)
1569         {
1570             OIC_LOG(ERROR, TAG, "add has failed");
1571             goto exit;
1572         }
1573
1574         if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
1575                             block2->num, block2->szx))
1576         {
1577             OIC_LOG(ERROR, TAG, "Data length is smaller than the start index");
1578             return CA_STATUS_FAILED;
1579         }
1580
1581         CALogBlockInfo(block2);
1582
1583         if (!block2->m)
1584         {
1585             // if sent message is last response block message, remove data
1586             CARemoveBlockDataFromList(blockID);
1587         }
1588     }
1589     else
1590     {
1591         OIC_LOG(DEBUG, TAG, "option2, not response msg");
1592         res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
1593         if (CA_STATUS_OK != res)
1594         {
1595             OIC_LOG(ERROR, TAG, "add has failed");
1596             goto exit;
1597         }
1598
1599         res = CAAddOptionToPDU(*pdu, options);
1600         if (CA_STATUS_OK != res)
1601         {
1602             OIC_LOG(ERROR, TAG, "add has failed");
1603             goto exit;
1604         }
1605         CALogBlockInfo(block2);
1606     }
1607
1608     return CA_STATUS_OK;
1609
1610 exit:
1611     CARemoveBlockDataFromList(blockID);
1612     return res;
1613 }
1614
1615 CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
1616                              const CABlockDataID_t *blockID, coap_list_t **options)
1617 {
1618     OIC_LOG(DEBUG, TAG, "IN-AddBlockOption1");
1619     VERIFY_NON_NULL(pdu, TAG, "pdu");
1620     VERIFY_NON_NULL((*pdu), TAG, "(*pdu)");
1621     VERIFY_NON_NULL((*pdu)->transport_hdr, TAG, "(*pdu)->transport_hdr");
1622     VERIFY_NON_NULL(info, TAG, "info");
1623     VERIFY_NON_NULL(blockID, TAG, "blockID");
1624     VERIFY_NON_NULL(options, TAG, "options");
1625
1626     // get set block data from CABlock list-set.
1627     coap_block_t *block1 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK1);
1628     if (!block1)
1629     {
1630         OIC_LOG(ERROR, TAG, "getting has failed");
1631         return CA_STATUS_FAILED;
1632     }
1633
1634     CAResult_t res = CA_STATUS_OK;
1635     uint32_t code = (*pdu)->transport_hdr->udp.code;
1636     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
1637     {
1638         CASetMoreBitFromBlock(dataLength, block1);
1639
1640         // if block number is 0, add size1 option
1641         if (0 == block1->num)
1642         {
1643             res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE1, dataLength, options);
1644             if (CA_STATUS_OK != res)
1645             {
1646                 OIC_LOG(ERROR, TAG, "add has failed");
1647                 goto exit;
1648             }
1649         }
1650
1651         // add block option to option list.
1652         res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
1653         if (CA_STATUS_OK != res)
1654         {
1655             OIC_LOG(ERROR, TAG, "add has failed");
1656             goto exit;
1657         }
1658
1659         // add option list to pdu.
1660         res = CAAddOptionToPDU(*pdu, options);
1661         if (CA_STATUS_OK != res)
1662         {
1663             OIC_LOG(ERROR, TAG, "add has failed");
1664             goto exit;
1665         }
1666
1667         // add the payload data as the block size.
1668         if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload, block1->num,
1669                             block1->szx))
1670         {
1671             OIC_LOG(ERROR, TAG, "Data length is smaller than the start index");
1672             return CA_STATUS_FAILED;
1673         }
1674     }
1675     else
1676     {
1677         OIC_LOG(DEBUG, TAG, "received response message with block option1");
1678
1679         // add block option to option list.
1680         res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
1681         if (CA_STATUS_OK != res)
1682         {
1683             OIC_LOG(ERROR, TAG, "add has failed");
1684             goto exit;
1685         }
1686
1687         // add option list to pdu.
1688         res = CAAddOptionToPDU(*pdu, options);
1689         if (CA_STATUS_OK != res)
1690         {
1691             OIC_LOG(ERROR, TAG, "add has failed");
1692             goto exit;
1693         }
1694
1695         // add the payload data as the block size.
1696         if (!coap_add_data(*pdu, dataLength, (const unsigned char *) info->payload))
1697         {
1698             OIC_LOG(ERROR, TAG, "failed to add payload");
1699             return CA_STATUS_FAILED;
1700         }
1701
1702         // if it is last block message, remove block data from list.
1703         if (0 == block1->m)
1704         {
1705             // remove data from list
1706             res = CARemoveBlockDataFromList(blockID);
1707             if (CA_STATUS_OK != res)
1708             {
1709                 OIC_LOG(ERROR, TAG, "remove has failed");
1710                 return res;
1711             }
1712         }
1713     }
1714
1715     CALogBlockInfo(block1);
1716
1717     OIC_LOG(DEBUG, TAG, "OUT-AddBlockOption1");
1718
1719     return CA_STATUS_OK;
1720
1721 exit:
1722     CARemoveBlockDataFromList(blockID);
1723     return res;
1724 }
1725
1726 CAResult_t CAAddBlockOptionImpl(coap_block_t *block, uint8_t blockType,
1727                                 coap_list_t **options)
1728 {
1729     OIC_LOG(DEBUG, TAG, "IN-AddBlockOptionImpl");
1730     VERIFY_NON_NULL(block, TAG, "block");
1731     VERIFY_NON_NULL(options, TAG, "options");
1732
1733     unsigned char buf[BLOCKWISE_OPTION_BUFFER] = { 0 };
1734     unsigned int optionLength = coap_encode_var_bytes(buf,
1735                                                       ((block->num << BLOCK_NUMBER_IDX)
1736                                                        | (block->m << BLOCK_M_BIT_IDX)
1737                                                        | block->szx));
1738
1739     int ret = coap_insert(options,
1740                           CACreateNewOptionNode(blockType, optionLength, (char *) buf),
1741                           CAOrderOpts);
1742     if (ret <= 0)
1743     {
1744         return CA_STATUS_INVALID_PARAM;
1745     }
1746
1747     OIC_LOG(DEBUG, TAG, "OUT-AddBlockOptionImpl");
1748     return CA_STATUS_OK;
1749 }
1750
1751 CAResult_t CAAddOptionToPDU(coap_pdu_t *pdu, coap_list_t **options)
1752 {
1753     // after adding the block option to option list, add option list to pdu.
1754     if (*options)
1755     {
1756         for (coap_list_t *opt = *options; opt; opt = opt->next)
1757         {
1758             OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
1759                       COAP_OPTION_DATA(*(coap_option *) opt->data));
1760
1761             OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
1762             int ret = coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
1763                                       COAP_OPTION_LENGTH(*(coap_option *) opt->data),
1764                                       COAP_OPTION_DATA(*(coap_option *) opt->data));
1765             if (!ret)
1766             {
1767                 return CA_STATUS_FAILED;
1768             }
1769         }
1770     }
1771
1772     OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
1773
1774     return CA_STATUS_OK;
1775 }
1776
1777 CAResult_t CAAddBlockSizeOption(coap_pdu_t *pdu, uint16_t sizeType, size_t dataLength,
1778                                 coap_list_t **options)
1779 {
1780     OIC_LOG(DEBUG, TAG, "IN-CAAddBlockSizeOption");
1781     VERIFY_NON_NULL(pdu, TAG, "pdu");
1782     VERIFY_NON_NULL(options, TAG, "options");
1783
1784     if (sizeType != COAP_OPTION_SIZE1 && sizeType != COAP_OPTION_SIZE2)
1785     {
1786         OIC_LOG(ERROR, TAG, "unknown option type");
1787         return CA_STATUS_FAILED;
1788     }
1789
1790     unsigned char value[BLOCKWISE_OPTION_BUFFER] = { 0 };
1791     unsigned int optionLength = coap_encode_var_bytes(value, dataLength);
1792
1793     int ret = coap_insert(options,
1794                           CACreateNewOptionNode(sizeType, optionLength, (char *) value),
1795                           CAOrderOpts);
1796     if (ret <= 0)
1797     {
1798         return CA_STATUS_INVALID_PARAM;
1799     }
1800
1801     OIC_LOG(DEBUG, TAG, "OUT-CAAddBlockSizeOption");
1802
1803     return CA_STATUS_OK;
1804 }
1805
1806 // TODO make pdu const after libcoap is updated to support that.
1807 bool CAIsPayloadLengthInPduWithBlockSizeOption(coap_pdu_t *pdu,
1808                                                uint16_t sizeType,
1809                                                size_t *totalPayloadLen)
1810 {
1811     OIC_LOG(DEBUG, TAG, "IN-CAIsPayloadLengthInPduWithBlockSizeOption");
1812     VERIFY_NON_NULL(pdu, TAG, "pdu");
1813     VERIFY_NON_NULL(totalPayloadLen, TAG, "totalPayloadLen");
1814
1815     if (sizeType != COAP_OPTION_SIZE1 && sizeType != COAP_OPTION_SIZE2)
1816     {
1817         OIC_LOG(ERROR, TAG, "unknown option type");
1818         return CA_STATUS_FAILED;
1819     }
1820
1821     coap_opt_iterator_t opt_iter;
1822     coap_opt_t *option = coap_check_option(pdu, sizeType, &opt_iter);
1823     if (option)
1824     {
1825         OIC_LOG(DEBUG, TAG, "get size option from pdu");
1826         *totalPayloadLen = coap_decode_var_bytes(COAP_OPT_VALUE(option),
1827                                                  COAP_OPT_LENGTH(option));
1828
1829         OIC_LOG_V(DEBUG, TAG, "the total payload length to be received is [%zu]bytes",
1830                   *totalPayloadLen);
1831
1832         return true;
1833     }
1834
1835     OIC_LOG(DEBUG, TAG, "OUT-CAIsPayloadLengthInPduWithBlockSizeOption");
1836
1837     return false;
1838 }
1839
1840 uint8_t CACheckBlockErrorType(CABlockData_t *currData, coap_block_t *receivedBlock,
1841                               const CAData_t *receivedData, uint16_t blockType,
1842                               size_t dataLen)
1843 {
1844     OIC_LOG(DEBUG, TAG, "IN-CheckBlockError");
1845
1846     VERIFY_NON_NULL(currData, TAG, "currData is NULL");
1847     VERIFY_NON_NULL(receivedBlock, TAG, "receivedBlock is NULL");
1848     VERIFY_NON_NULL(receivedData, TAG, "receivedData is NULL");
1849
1850     // #1. check the received payload length
1851     size_t blockPayloadLen = 0;
1852     CAGetPayloadInfo(receivedData, &blockPayloadLen);
1853
1854     // #2. check if the block sequence is right
1855     if (COAP_OPTION_BLOCK1 == blockType)
1856     {
1857         size_t prePayloadLen = currData->receivedPayloadLen;
1858         if (prePayloadLen != (size_t) BLOCK_SIZE(receivedBlock->szx) * receivedBlock->num)
1859         {
1860             if (receivedBlock->num > currData->block1.num + 1)
1861             {
1862                 // 408 Error handling of block loss
1863                 OIC_LOG(ERROR, TAG, "option1: error 4.08");
1864                 OIC_LOG(ERROR, TAG, "it didn't order");
1865                 return CA_BLOCK_INCOMPLETE;
1866             }
1867             return CA_BLOCK_RECEIVED_ALREADY;
1868         }
1869     }
1870     else if (COAP_OPTION_BLOCK2 == blockType)
1871     {
1872         if (receivedBlock->num != currData->block2.num)
1873         {
1874             if (receivedBlock->num > currData->block2.num)
1875             {
1876                 // 408 Error handling of block loss
1877                 OIC_LOG(ERROR, TAG, "option2: error 4.08");
1878                 OIC_LOG(ERROR, TAG, "it didn't order");
1879                 return CA_BLOCK_INCOMPLETE;
1880             }
1881             else
1882             {
1883                 OIC_LOG(ERROR, TAG, "already received this block");
1884                 return CA_BLOCK_RECEIVED_ALREADY;
1885             }
1886         }
1887     }
1888
1889     // #3. check if error check logic is required
1890     size_t optionLen = dataLen - blockPayloadLen;
1891     if (receivedBlock->m && blockPayloadLen != (size_t) BLOCK_SIZE(receivedBlock->szx))
1892     {
1893         // 413 Error handling of too large entity
1894         if (COAP_MAX_PDU_SIZE < BLOCK_SIZE(receivedBlock->szx) + optionLen)
1895         {
1896             // buffer size is smaller than received block size
1897             OIC_LOG(ERROR, TAG, "error type 4.13");
1898             OIC_LOG(ERROR, TAG, "too large size");
1899
1900             // set the block size to be smaller than COAP_MAX_PDU_SIZE
1901             for (int32_t size = CA_DEFAULT_BLOCK_SIZE; size >= 0; size--)
1902             {
1903                 if (COAP_MAX_PDU_SIZE >= BLOCK_SIZE(size) + optionLen)
1904                 {
1905                     OIC_LOG_V(ERROR, TAG, "replace sze with %d", size);
1906                     currData->block2.szx = size;
1907                     currData->block1.szx = size;
1908                     break;
1909                 }
1910             }
1911             return CA_BLOCK_TOO_LARGE;
1912         }
1913         else
1914         {
1915             // 408 Error handling of payload loss
1916             OIC_LOG(ERROR, TAG, "error type 4.08");
1917             OIC_LOG(ERROR, TAG, "payload len != block sze");
1918             return CA_BLOCK_INCOMPLETE;
1919         }
1920     }
1921     else if (0 == receivedBlock->m && 0 != currData->payloadLength)
1922     {
1923         // if the received block is last block, check the total payload length
1924         size_t receivedPayloadLen = currData->receivedPayloadLen;
1925         receivedPayloadLen += blockPayloadLen;
1926
1927         if (receivedPayloadLen != currData->payloadLength)
1928         {
1929             OIC_LOG(ERROR, TAG, "error type 4.08");
1930             OIC_LOG(ERROR, TAG, "total payload length is wrong");
1931             return CA_BLOCK_INCOMPLETE;
1932         }
1933     }
1934
1935     OIC_LOG(DEBUG, TAG, "received all data normally");
1936
1937     OIC_LOG(DEBUG, TAG, "OUT-CheckBlockError");
1938
1939     return CA_BLOCK_UNKNOWN;
1940 }
1941
1942 CAResult_t CAUpdatePayloadData(CABlockData_t *currData, const CAData_t *receivedData,
1943                                uint8_t status, bool isSizeOption, uint16_t blockType)
1944 {
1945     OIC_LOG(DEBUG, TAG, "IN-UpdatePayloadData");
1946
1947     VERIFY_NON_NULL(currData, TAG, "currData");
1948     VERIFY_NON_NULL(receivedData, TAG, "receivedData");
1949
1950     // if error code is 4.08, do not update payload
1951     if (CA_BLOCK_INCOMPLETE == status)
1952     {
1953         OIC_LOG(ERROR, TAG, "no require to update");
1954         return CA_STATUS_OK;
1955     }
1956
1957     size_t blockPayloadLen = 0;
1958     CAPayload_t blockPayload = CAGetPayloadInfo(receivedData, &blockPayloadLen);
1959
1960     if (CA_BLOCK_TOO_LARGE == status)
1961     {
1962         blockPayloadLen = (COAP_OPTION_BLOCK2 == blockType) ?
1963                 BLOCK_SIZE(currData->block2.szx) : BLOCK_SIZE(currData->block1.szx);
1964     }
1965
1966     // memory allocation for the received block payload
1967     size_t prePayloadLen = currData->receivedPayloadLen;
1968     if (blockPayload)
1969     {
1970         if (currData->payloadLength)
1971         {
1972             // in case the block message has the size option
1973             // allocate the memory for the total payload
1974             if (isSizeOption)
1975             {
1976                 CAPayload_t prePayload = currData->payload;
1977
1978                 OIC_LOG(DEBUG, TAG, "allocate memory for the total payload");
1979                 currData->payload = (CAPayload_t) OICCalloc(1, currData->payloadLength);
1980                 if (NULL == currData->payload)
1981                 {
1982                     OIC_LOG(ERROR, TAG, "out of memory");
1983                     return CA_MEMORY_ALLOC_FAILED;
1984                 }
1985                 memcpy(currData->payload, prePayload, prePayloadLen);
1986                 OICFree(prePayload);
1987             }
1988
1989             // update the total payload
1990             memcpy(currData->payload + prePayloadLen, blockPayload, blockPayloadLen);
1991         }
1992         else
1993         {
1994             OIC_LOG(DEBUG, TAG, "allocate memory for the received block payload");
1995
1996             size_t totalPayloadLen = prePayloadLen + blockPayloadLen;
1997             CAPayload_t newPayload = OICRealloc(currData->payload, totalPayloadLen);
1998             if (NULL == newPayload)
1999             {
2000                 OIC_LOG(ERROR, TAG, "out of memory");
2001                 return CA_MEMORY_ALLOC_FAILED;
2002             }
2003
2004             // update the total payload
2005             memset(newPayload + prePayloadLen, 0, blockPayloadLen);
2006             currData->payload = newPayload;
2007             memcpy(currData->payload + prePayloadLen, blockPayload, blockPayloadLen);
2008         }
2009
2010         // update received payload length
2011         currData->receivedPayloadLen += blockPayloadLen;
2012
2013         OIC_LOG_V(DEBUG, TAG, "updated payload: %s, len: %zu", currData->payload,
2014                   currData->receivedPayloadLen);
2015     }
2016
2017     OIC_LOG(DEBUG, TAG, "OUT-UpdatePayloadData");
2018     return CA_STATUS_OK;
2019 }
2020
2021 CAData_t* CACreateNewDataSet(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
2022 {
2023     VERIFY_NON_NULL_RET(pdu, TAG, "pdu", NULL);
2024     VERIFY_NON_NULL_RET(pdu->transport_hdr, TAG, "pdu->transport_hdr", NULL);
2025     VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
2026
2027     CARequestInfo_t* requestInfo = NULL;
2028     CAResponseInfo_t* responseInfo = NULL;
2029
2030     uint32_t code = pdu->transport_hdr->udp.code;
2031     if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code)
2032     {
2033         CAInfo_t responseData = { .tokenLength = pdu->transport_hdr->udp.token_length };
2034         responseData.token = (CAToken_t) OICMalloc(responseData.tokenLength);
2035         if (!responseData.token)
2036         {
2037             OIC_LOG(ERROR, TAG, "out of memory");
2038             return NULL;
2039         }
2040         memcpy(responseData.token, pdu->transport_hdr->udp.token, responseData.tokenLength);
2041
2042         responseInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
2043         if (!responseInfo)
2044         {
2045             OIC_LOG(ERROR, TAG, "out of memory");
2046             OICFree(responseData.token);
2047             return NULL;
2048         }
2049         responseInfo->info = responseData;
2050     }
2051     else
2052     {
2053         CAInfo_t requestData = { .tokenLength = pdu->transport_hdr->udp.token_length };
2054         requestData.token = (CAToken_t) OICMalloc(requestData.tokenLength);
2055         if (!requestData.token)
2056         {
2057             OIC_LOG(ERROR, TAG, "out of memory");
2058             return NULL;
2059         }
2060         memcpy(requestData.token, pdu->transport_hdr->udp.token, requestData.tokenLength);
2061
2062         requestInfo = (CARequestInfo_t*) OICCalloc(1, sizeof(CARequestInfo_t));
2063         if (!requestInfo)
2064         {
2065             OIC_LOG(ERROR, TAG, "out of memory");
2066             OICFree(requestData.token);
2067             return NULL;
2068         }
2069         requestInfo->info = requestData;
2070
2071         // get resource uri information from received response message
2072         // to send next request message to remote device
2073         CAResponseInfo_t* resInfo = (CAResponseInfo_t*)OICCalloc(1, sizeof(*resInfo));
2074         if (!resInfo)
2075         {
2076             OIC_LOG(ERROR, TAG, "memory allocation failed");
2077             OICFree(requestData.token);
2078             OICFree(requestInfo);
2079             return NULL;
2080         }
2081
2082         CAGetResponseInfoFromPDU(pdu, resInfo, endpoint);
2083         requestInfo->method = CA_GET;
2084         requestInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu->transport_hdr,
2085                                                                       pdu->length);
2086         requestInfo->info.resourceUri = OICStrdup(resInfo->info.resourceUri);
2087
2088         // after copying the resource uri, destroy response info.
2089         CADestroyResponseInfoInternal(resInfo);
2090     }
2091
2092     CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
2093     if (!data)
2094     {
2095         OIC_LOG(ERROR, TAG, "out of memory");
2096         if (NULL != requestInfo)
2097         {
2098             OICFree(requestInfo->info.resourceUri);
2099             OICFree(requestInfo->info.token);
2100             OICFree(requestInfo);
2101         }
2102         if (NULL != responseInfo)
2103         {
2104             OICFree(responseInfo->info.token);
2105             OICFree(responseInfo);
2106         }
2107         return NULL;
2108     }
2109
2110     data->requestInfo = requestInfo;
2111     data->responseInfo = responseInfo;
2112     data->remoteEndpoint = CACloneEndpoint(endpoint);
2113     data->type = SEND_TYPE_UNICAST;
2114
2115     return data;
2116 }
2117
2118 CAData_t *CACloneCAData(const CAData_t *data)
2119 {
2120     VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
2121
2122     CAData_t *clone = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
2123     if (!clone)
2124     {
2125         OIC_LOG(ERROR, TAG, "out of memory");
2126         return NULL;
2127     }
2128     *clone = *data;
2129
2130     if (data->requestInfo)
2131     {
2132         clone->requestInfo = CACloneRequestInfo(data->requestInfo);
2133     }
2134     else if (data->responseInfo)
2135     {
2136         clone->responseInfo = CACloneResponseInfo(data->responseInfo);
2137     }
2138
2139     if (data->remoteEndpoint)
2140     {
2141         clone->remoteEndpoint = CACloneEndpoint(data->remoteEndpoint);
2142     }
2143
2144     return clone;
2145 }
2146
2147 CAResult_t CAUpdatePayloadToCAData(CAData_t *data, const CAPayload_t payload,
2148                                    size_t payloadLen)
2149 {
2150     OIC_LOG(DEBUG, TAG, "IN-UpdatePayload");
2151
2152     VERIFY_NON_NULL(data, TAG, "data is NULL");
2153     VERIFY_NON_NULL(payload, TAG, "payload is NULL");
2154
2155     CAPayload_t newPayload = NULL;
2156     switch (data->dataType)
2157     {
2158         case CA_REQUEST_DATA:
2159             if (!data->requestInfo)
2160             {
2161                 OIC_LOG(ERROR, TAG, "request info is null");
2162                 return CA_STATUS_FAILED;
2163             }
2164             // allocate payload field
2165             newPayload = OICRealloc(data->requestInfo->info.payload, payloadLen);
2166             if (!newPayload)
2167             {
2168                 OIC_LOG(ERROR, TAG, "out of memory");
2169                 return CA_STATUS_FAILED;
2170             }
2171             data->requestInfo->info.payload = newPayload;
2172             memcpy(data->requestInfo->info.payload, payload, payloadLen);
2173             data->requestInfo->info.payloadSize = payloadLen;
2174             break;
2175
2176         case CA_RESPONSE_DATA:
2177             if (!data->responseInfo)
2178             {
2179                 OIC_LOG(ERROR, TAG, "response info is null");
2180                 return CA_STATUS_FAILED;
2181             }
2182             // allocate payload field
2183             newPayload = OICRealloc(data->responseInfo->info.payload, payloadLen);
2184             if (!newPayload)
2185             {
2186                 OIC_LOG(ERROR, TAG, "out of memory");
2187                 return CA_STATUS_FAILED;
2188             }
2189             data->responseInfo->info.payload = newPayload;
2190             memcpy(data->responseInfo->info.payload, payload, payloadLen);
2191             data->responseInfo->info.payloadSize = payloadLen;
2192             break;
2193
2194         default:
2195             // does not occur case
2196             OIC_LOG(ERROR, TAG, "not supported data type");
2197             return CA_NOT_SUPPORTED;
2198     }
2199
2200     OIC_LOG(DEBUG, TAG, "OUT-UpdatePayload");
2201
2202     return CA_STATUS_OK;
2203 }
2204
2205 CAPayload_t CAGetPayloadInfo(const CAData_t *data, size_t *payloadLen)
2206 {
2207     VERIFY_NON_NULL_RET(data, TAG, "data", NULL);
2208     VERIFY_NON_NULL_RET(payloadLen, TAG, "payloadLen", NULL);
2209
2210     if (data->requestInfo)
2211     {
2212         if (data->requestInfo->info.payload)
2213         {
2214             *payloadLen = data->requestInfo->info.payloadSize;
2215             return data->requestInfo->info.payload;
2216         }
2217     }
2218     else if (data->responseInfo)
2219     {
2220         if (data->responseInfo->info.payload)
2221         {
2222             *payloadLen = data->responseInfo->info.payloadSize;
2223             return data->responseInfo->info.payload;
2224         }
2225     }
2226
2227     return NULL;
2228 }
2229
2230 CAResult_t CAHandleBlockErrorResponse(coap_block_t *block, uint16_t blockType,
2231                                       uint32_t responseResult)
2232 {
2233     OIC_LOG(DEBUG, TAG, "IN-HandleBlockErrorRes");
2234     VERIFY_NON_NULL(block, TAG, "block is NULL");
2235
2236     // update block data
2237     switch (responseResult)
2238     {
2239         case CA_REQUEST_ENTITY_INCOMPLETE:
2240             block->num = 0;
2241             break;
2242         case CA_REQUEST_ENTITY_TOO_LARGE:
2243             if (COAP_OPTION_BLOCK1 == blockType)
2244             {
2245                 block->num++;
2246             }
2247             block->m = 0;
2248             break;
2249         default:
2250             OIC_LOG_V(ERROR, TAG, "there is no Error Code of BWT[%d]", responseResult);
2251             return CA_STATUS_FAILED;
2252     }
2253
2254     OIC_LOG(DEBUG, TAG, "OUT-HandleBlockErrorRes");
2255     return CA_STATUS_OK;
2256 }
2257
2258 CAResult_t CAUpdateBlockOptionType(const CABlockDataID_t *blockID, uint8_t blockType)
2259 {
2260     OIC_LOG(DEBUG, TAG, "IN-UpdateBlockOptionType");
2261     VERIFY_NON_NULL(blockID, TAG, "blockID");
2262
2263     oc_mutex_lock(g_context.blockDataListMutex);
2264
2265     size_t len = u_arraylist_length(g_context.dataList);
2266     for (size_t i = 0; i < len; i++)
2267     {
2268         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2269         if (CABlockidMatches(currData, blockID))
2270         {
2271             currData->type = blockType;
2272             oc_mutex_unlock(g_context.blockDataListMutex);
2273             OIC_LOG(DEBUG, TAG, "OUT-UpdateBlockOptionType");
2274             return CA_STATUS_OK;
2275         }
2276     }
2277     oc_mutex_unlock(g_context.blockDataListMutex);
2278
2279     OIC_LOG(DEBUG, TAG, "OUT-UpdateBlockOptionType");
2280     return CA_STATUS_FAILED;
2281 }
2282
2283 uint8_t CAGetBlockOptionType(const CABlockDataID_t *blockID)
2284 {
2285     OIC_LOG(DEBUG, TAG, "IN-GetBlockOptionType");
2286     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", 0);
2287
2288     oc_mutex_lock(g_context.blockDataListMutex);
2289
2290     size_t len = u_arraylist_length(g_context.dataList);
2291     for (size_t i = 0; i < len; i++)
2292     {
2293         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2294         if (CABlockidMatches(currData, blockID))
2295         {
2296             oc_mutex_unlock(g_context.blockDataListMutex);
2297             OIC_LOG(DEBUG, TAG, "OUT-GetBlockOptionType");
2298             return currData->type;
2299         }
2300     }
2301     oc_mutex_unlock(g_context.blockDataListMutex);
2302
2303     OIC_LOG(DEBUG, TAG, "OUT-GetBlockOptionType");
2304     return 0;
2305 }
2306
2307 CAData_t *CAGetDataSetFromBlockDataList(const CABlockDataID_t *blockID)
2308 {
2309     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
2310
2311     oc_mutex_lock(g_context.blockDataListMutex);
2312
2313     size_t len = u_arraylist_length(g_context.dataList);
2314     for (size_t i = 0; i < len; i++)
2315     {
2316         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2317         if (CABlockidMatches(currData, blockID))
2318         {
2319             oc_mutex_unlock(g_context.blockDataListMutex);
2320             return currData->sentData;
2321         }
2322     }
2323     oc_mutex_unlock(g_context.blockDataListMutex);
2324
2325     return NULL;
2326 }
2327
2328 CABlockData_t *CAUpdateDataSetFromBlockDataList(const CABlockDataID_t *blockID,
2329                                                 const CAData_t *sendData)
2330 {
2331     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
2332     VERIFY_NON_NULL_RET(sendData, TAG, "sendData", NULL);
2333
2334     oc_mutex_lock(g_context.blockDataListMutex);
2335
2336     size_t len = u_arraylist_length(g_context.dataList);
2337     for (size_t i = 0; i < len; i++)
2338     {
2339         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2340         if (CABlockidMatches(currData, blockID))
2341         {
2342             CADestroyDataSet(currData->sentData);
2343             currData->sentData = CACloneCAData(sendData);
2344             oc_mutex_unlock(g_context.blockDataListMutex);
2345             return currData;
2346         }
2347     }
2348     oc_mutex_unlock(g_context.blockDataListMutex);
2349
2350     return NULL;
2351 }
2352
2353 CAResult_t CAGetTokenFromBlockDataList(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
2354                                        CAResponseInfo_t *responseInfo)
2355 {
2356     OIC_LOG(DEBUG, TAG, "IN-CAGetTokenFromBlockDataList");
2357     VERIFY_NON_NULL(pdu, TAG, "pdu");
2358     VERIFY_NON_NULL(endpoint, TAG, "endpoint");
2359     VERIFY_NON_NULL(responseInfo, TAG, "responseInfo");
2360
2361     oc_mutex_lock(g_context.blockDataListMutex);
2362
2363     size_t len = u_arraylist_length(g_context.dataList);
2364     for (size_t i = 0; i < len; i++)
2365     {
2366         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2367         if (NULL == currData)
2368         {
2369             continue;
2370         }
2371
2372         if (NULL != currData->sentData && NULL != currData->sentData->requestInfo)
2373         {
2374             if (pdu->transport_hdr->udp.id == currData->sentData->requestInfo->info.messageId &&
2375                     endpoint->adapter == currData->sentData->remoteEndpoint->adapter)
2376             {
2377                 if (NULL != currData->sentData->requestInfo->info.token)
2378                 {
2379                     uint8_t length = currData->sentData->requestInfo->info.tokenLength;
2380                     responseInfo->info.tokenLength = length;
2381                     responseInfo->info.token = (char *) OICMalloc(length);
2382                     if (NULL == responseInfo->info.token)
2383                     {
2384                         OIC_LOG(ERROR, TAG, "out of memory");
2385                         oc_mutex_unlock(g_context.blockDataListMutex);
2386                         return CA_MEMORY_ALLOC_FAILED;
2387                     }
2388                     memcpy(responseInfo->info.token, currData->sentData->requestInfo->info.token,
2389                            responseInfo->info.tokenLength);
2390
2391                     oc_mutex_unlock(g_context.blockDataListMutex);
2392                     OIC_LOG(DEBUG, TAG, "OUT-CAGetTokenFromBlockDataList");
2393                     return CA_STATUS_OK;
2394                 }
2395             }
2396         }
2397     }
2398
2399     oc_mutex_unlock(g_context.blockDataListMutex);
2400
2401     OIC_LOG(DEBUG, TAG, "OUT-CAGetTokenFromBlockDataList");
2402     return CA_STATUS_FAILED;
2403 }
2404
2405 CAResult_t CACheckBlockDataValidation(const CAData_t *sendData, CABlockData_t **blockData)
2406 {
2407     VERIFY_NON_NULL(sendData, TAG, "sendData");
2408     VERIFY_NON_NULL(blockData, TAG, "blockData");
2409
2410     if (sendData->responseInfo)
2411     {
2412         CABlockDataID_t* blockDataID = CACreateBlockDatablockId(
2413                 (CAToken_t)sendData->responseInfo->info.token,
2414                 sendData->responseInfo->info.tokenLength,
2415                 sendData->remoteEndpoint->port);
2416         if (NULL == blockDataID || blockDataID->idLength < 1)
2417         {
2418             OIC_LOG(ERROR, TAG, "blockId is null");
2419             CADestroyBlockID(blockDataID);
2420             return CA_STATUS_FAILED;
2421         }
2422
2423         CABlockData_t *updatedData = CAUpdateDataSetFromBlockDataList(blockDataID, sendData);
2424         if (updatedData)
2425         {
2426             OIC_LOG(DEBUG, TAG, "Send response about the received block request.");
2427             *blockData = updatedData;
2428             CADestroyBlockID(blockDataID);
2429             return CA_STATUS_OK;
2430         }
2431         CADestroyBlockID(blockDataID);
2432     }
2433
2434     return CA_STATUS_FAILED;
2435 }
2436
2437 CABlockData_t *CAGetBlockDataFromBlockDataList(const CABlockDataID_t *blockID)
2438 {
2439     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
2440
2441     oc_mutex_lock(g_context.blockDataListMutex);
2442
2443     size_t len = u_arraylist_length(g_context.dataList);
2444     for (size_t i = 0; i < len; i++)
2445     {
2446         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2447         if (CABlockidMatches(currData, blockID))
2448         {
2449             oc_mutex_unlock(g_context.blockDataListMutex);
2450             return currData;
2451         }
2452     }
2453     oc_mutex_unlock(g_context.blockDataListMutex);
2454
2455     return NULL;
2456 }
2457
2458 coap_block_t *CAGetBlockOption(const CABlockDataID_t *blockID, uint16_t blockType)
2459 {
2460     OIC_LOG(DEBUG, TAG, "IN-GetBlockOption");
2461     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
2462
2463     oc_mutex_lock(g_context.blockDataListMutex);
2464
2465     size_t len = u_arraylist_length(g_context.dataList);
2466     for (size_t i = 0; i < len; i++)
2467     {
2468         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2469         if (CABlockidMatches(currData, blockID))
2470         {
2471             oc_mutex_unlock(g_context.blockDataListMutex);
2472             OIC_LOG(DEBUG, TAG, "OUT-GetBlockOption");
2473             if (COAP_OPTION_BLOCK2 == blockType)
2474             {
2475                 return &currData->block2;
2476             }
2477             else if (COAP_OPTION_BLOCK1 == blockType)
2478             {
2479                 return &currData->block1;
2480             }
2481         }
2482     }
2483     oc_mutex_unlock(g_context.blockDataListMutex);
2484
2485     OIC_LOG(DEBUG, TAG, "OUT-GetBlockOption");
2486     return NULL;
2487 }
2488
2489 CAPayload_t CAGetPayloadFromBlockDataList(const CABlockDataID_t *blockID,
2490                                           size_t *fullPayloadLen)
2491 {
2492     OIC_LOG(DEBUG, TAG, "IN-GetFullPayload");
2493     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", NULL);
2494     VERIFY_NON_NULL_RET(fullPayloadLen, TAG, "fullPayloadLen", NULL);
2495
2496     oc_mutex_lock(g_context.blockDataListMutex);
2497
2498     size_t len = u_arraylist_length(g_context.dataList);
2499     for (size_t i = 0; i < len; i++)
2500     {
2501         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2502         if (CABlockidMatches(currData, blockID))
2503         {
2504             oc_mutex_unlock(g_context.blockDataListMutex);
2505             *fullPayloadLen = currData->receivedPayloadLen;
2506             OIC_LOG(DEBUG, TAG, "OUT-GetFullPayload");
2507             return currData->payload;
2508         }
2509     }
2510     oc_mutex_unlock(g_context.blockDataListMutex);
2511
2512     OIC_LOG(DEBUG, TAG, "OUT-GetFullPayload");
2513     return NULL;
2514 }
2515
2516 CABlockData_t *CACreateNewBlockData(const CAData_t *sendData)
2517 {
2518     OIC_LOG(DEBUG, TAG, "IN-CACreateNewBlockData");
2519     VERIFY_NON_NULL_RET(sendData, TAG, "sendData", NULL);
2520
2521     // create block data
2522     CABlockData_t *data = (CABlockData_t *) OICCalloc(1, sizeof(CABlockData_t));
2523     if (!data)
2524     {
2525         OIC_LOG(ERROR, TAG, "memory alloc has failed");
2526         return NULL;
2527     }
2528
2529     data->block1.szx = CA_DEFAULT_BLOCK_SIZE;
2530     data->block2.szx = CA_DEFAULT_BLOCK_SIZE;
2531     data->sentData = CACloneCAData(sendData);
2532     if (!data->sentData)
2533     {
2534         OIC_LOG(ERROR, TAG, PCF("memory alloc has failed"));
2535         OICFree(data);
2536         return NULL;
2537     }
2538
2539     CAToken_t token = NULL;
2540     uint8_t tokenLength = 0;
2541     if (data->sentData->requestInfo)
2542     {
2543         // update token info
2544         tokenLength = data->sentData->requestInfo->info.tokenLength;
2545         token = data->sentData->requestInfo->info.token;
2546     }
2547     else if (data->sentData->responseInfo)
2548     {
2549         tokenLength = data->sentData->responseInfo->info.tokenLength;
2550         token = data->sentData->responseInfo->info.token;
2551     }
2552
2553     if (!data->sentData->remoteEndpoint)
2554     {
2555         OIC_LOG(ERROR, TAG, "remoteEndpoint is null");
2556         CADestroyDataSet(data->sentData);
2557         OICFree(data);
2558         return NULL;
2559     }
2560
2561     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(token, tokenLength,
2562                                                             data->sentData->remoteEndpoint->port);
2563     if (NULL == blockDataID || blockDataID->idLength < 1)
2564     {
2565         OIC_LOG(ERROR, TAG, "blockId is null");
2566         CADestroyBlockID(blockDataID);
2567         CADestroyDataSet(data->sentData);
2568         OICFree(data);
2569         return NULL;
2570     }
2571     data->blockDataId = blockDataID;
2572     uint64_t now = OICGetCurrentTime(TIME_IN_US);
2573     data->ttl = now + (BLOCK_DATA_TIMEOUT_SECONDS * USECS_PER_SEC);
2574
2575     oc_mutex_lock(g_context.blockDataListMutex);
2576
2577     bool res = u_arraylist_add(g_context.dataList, (void *) data);
2578     if (!res)
2579     {
2580         OIC_LOG(ERROR, TAG, "add has failed");
2581         CADestroyBlockID(data->blockDataId);
2582         CADestroyDataSet(data->sentData);
2583         OICFree(data);
2584         oc_mutex_unlock(g_context.blockDataListMutex);
2585         return NULL;
2586     }
2587     oc_mutex_unlock(g_context.blockDataListMutex);
2588
2589     OIC_LOG(DEBUG, TAG, "OUT-CreateBlockData");
2590     return data;
2591 }
2592
2593 CAResult_t CARemoveBlockDataFromList(const CABlockDataID_t *blockID)
2594 {
2595     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2596     VERIFY_NON_NULL(blockID, TAG, "blockID");
2597
2598     oc_mutex_lock(g_context.blockDataListMutex);
2599
2600     size_t len = u_arraylist_length(g_context.dataList);
2601     for (size_t i = 0; i < len; i++)
2602     {
2603         CABlockData_t *currData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2604         if (CABlockidMatches(currData, blockID))
2605         {
2606             CABlockData_t *removedData = u_arraylist_remove(g_context.dataList, i);
2607             if (!removedData)
2608             {
2609                 OIC_LOG(ERROR, TAG, "data is NULL");
2610                 oc_mutex_unlock(g_context.blockDataListMutex);
2611                 return CA_STATUS_FAILED;
2612             }
2613
2614             OIC_LOG(DEBUG, TAG, "Removed BlockID is ");
2615             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) removedData->blockDataId->id,
2616                            removedData->blockDataId->idLength);
2617
2618             // destroy memory
2619             CADestroyDataSet(removedData->sentData);
2620             CADestroyBlockID(removedData->blockDataId);
2621             OICFree(removedData->payload);
2622             OICFree(removedData);
2623             oc_mutex_unlock(g_context.blockDataListMutex);
2624             return CA_STATUS_OK;
2625         }
2626     }
2627     oc_mutex_unlock(g_context.blockDataListMutex);
2628     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2629     return CA_STATUS_OK;
2630 }
2631
2632 CAResult_t CARemoveAllBlockDataFromList()
2633 {
2634     OIC_LOG(DEBUG, TAG, "CARemoveAllBlockDataFromList");
2635
2636     oc_mutex_lock(g_context.blockDataListMutex);
2637
2638     size_t len = u_arraylist_length(g_context.dataList);
2639     for (size_t i = len; i > 0; i--)
2640     {
2641         CABlockData_t *removedData = u_arraylist_remove(g_context.dataList, i - 1);
2642         if (removedData)
2643         {
2644             // destroy memory
2645             if (removedData->sentData)
2646             {
2647                 CADestroyDataSet(removedData->sentData);
2648             }
2649             CADestroyBlockID(removedData->blockDataId);
2650             OICFree(removedData->payload);
2651             OICFree(removedData);
2652         }
2653     }
2654     oc_mutex_unlock(g_context.blockDataListMutex);
2655
2656     return CA_STATUS_OK;
2657 }
2658
2659 void CADestroyDataSet(CAData_t* data)
2660 {
2661     VERIFY_NON_NULL_VOID(data, TAG, "data");
2662
2663     if (data->remoteEndpoint)
2664     {
2665         CAFreeEndpoint(data->remoteEndpoint);
2666         data->remoteEndpoint = NULL;
2667     }
2668     if (data->requestInfo)
2669     {
2670         CADestroyRequestInfoInternal(data->requestInfo);
2671         data->requestInfo = NULL;
2672     }
2673     if (data->responseInfo)
2674     {
2675         CADestroyResponseInfoInternal(data->responseInfo);
2676         data->responseInfo = NULL;
2677     }
2678     OICFree(data);
2679 }
2680
2681 CABlockDataID_t* CACreateBlockDatablockId(const CAToken_t token, uint8_t tokenLength,
2682                                           uint16_t portNumber)
2683 {
2684     char port[PORT_LENGTH] = { 0, };
2685     port[0] = (char) ((portNumber >> 8) & 0xFF);
2686     port[1] = (char) (portNumber & 0xFF);
2687
2688     CABlockDataID_t* blockDataID = (CABlockDataID_t *) OICMalloc(sizeof(CABlockDataID_t));
2689     if (!blockDataID)
2690     {
2691         OIC_LOG(ERROR, TAG, "memory alloc has failed");
2692         return NULL;
2693     }
2694     blockDataID->idLength = tokenLength + sizeof(port);
2695     blockDataID->id = (uint8_t *) OICMalloc(blockDataID->idLength);
2696     if (!blockDataID->id)
2697     {
2698         OIC_LOG(ERROR, TAG, "memory alloc has failed");
2699         OICFree(blockDataID);
2700         return NULL;
2701     }
2702
2703     if (token)
2704     {
2705         memcpy(blockDataID->id, token, tokenLength);
2706     }
2707
2708     memcpy(blockDataID->id + tokenLength, port, sizeof(port));
2709
2710     OIC_LOG(DEBUG, TAG, "BlockID is ");
2711     OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)blockDataID->id, blockDataID->idLength);
2712
2713     return blockDataID;
2714 }
2715
2716 void CADestroyBlockID(CABlockDataID_t *blockID)
2717 {
2718     VERIFY_NON_NULL_VOID(blockID, TAG, "blockID");
2719     OICFree(blockID->id);
2720     OICFree(blockID);
2721     blockID = NULL;
2722 }
2723
2724 bool CABlockidMatches(const CABlockData_t *currData, const CABlockDataID_t *blockID)
2725 {
2726     VERIFY_NON_NULL_RET(currData, TAG, "currData", false);
2727     VERIFY_NON_NULL_RET(blockID, TAG, "blockID", false);
2728     VERIFY_NON_NULL_RET(blockID->id, TAG, "blockID->id", false);
2729
2730     if ((currData->blockDataId)
2731         && (currData->blockDataId->id)
2732         && (currData->blockDataId->idLength == blockID->idLength)
2733         && !memcmp(currData->blockDataId->id, blockID->id, currData->blockDataId->idLength))
2734     {
2735         return true;
2736     }
2737     return false;
2738 }
2739
2740 void CALogBlockInfo(coap_block_t *block)
2741 {
2742     VERIFY_NON_NULL_VOID(block, TAG, "block");
2743
2744     OIC_LOG(DEBUG, TAG, "block option info");
2745
2746     OIC_LOG_V(DEBUG, TAG, "block option-num : %d", block->num);
2747
2748     OIC_LOG_V(DEBUG, TAG, "block option-m   : %d", block->m);
2749
2750     OIC_LOG_V(DEBUG, TAG, "block option-szx : %d", block->szx);
2751 }
2752
2753 CAResult_t CARemoveBlockDataFromListWithSeed(const CAToken_t token, uint8_t tokenLength,
2754                                              uint16_t portNumber)
2755 {
2756     CABlockDataID_t* blockDataID = CACreateBlockDatablockId(token, tokenLength, portNumber);
2757     if (NULL == blockDataID || blockDataID->idLength < 1)
2758     {
2759         OIC_LOG(ERROR, TAG, "blockId is null");
2760         CADestroyBlockID(blockDataID);
2761         return CA_STATUS_FAILED;
2762     }
2763
2764     CAResult_t res = CARemoveBlockDataFromList(blockDataID);
2765     if (CA_STATUS_OK != res)
2766     {
2767         OIC_LOG(ERROR, TAG, "CARemoveBlockDataFromList failed");
2768     }
2769
2770     CADestroyBlockID(blockDataID);
2771     return res;
2772 }
2773
2774 void CAResetBlockDataTTL(const CABlockDataID_t *blockID)
2775 {
2776     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2777
2778     oc_mutex_lock(g_context.blockDataListMutex);
2779     size_t len = u_arraylist_length(g_context.dataList);
2780     for (size_t i = 0; i < len; i++)
2781     {
2782         CABlockData_t *blockData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2783         if (CABlockidMatches(blockData, blockID))
2784         {
2785             uint64_t now = OICGetCurrentTime(TIME_IN_US);
2786             blockData->ttl = now + (BLOCK_DATA_TIMEOUT_SECONDS * USECS_PER_SEC);
2787             oc_mutex_unlock(g_context.blockDataListMutex);
2788             OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2789             return;
2790         }
2791     }
2792     oc_mutex_unlock(g_context.blockDataListMutex);
2793     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2794 }
2795
2796 void CACheckAndDeleteTimedOutBlockData()
2797 {
2798     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2799
2800     uint64_t now = OICGetCurrentTime(TIME_IN_US);
2801
2802     oc_mutex_lock(g_context.blockDataListMutex);
2803     for (size_t i = 0; i < u_arraylist_length(g_context.dataList); i++)
2804     {
2805         CABlockData_t *blockData = (CABlockData_t *) u_arraylist_get(g_context.dataList, i);
2806         if (blockData && blockData->ttl < now)
2807         {
2808             OIC_LOG(INFO, TAG, "Deleting timed-out BlockData");
2809             OIC_LOG(DEBUG, TAG, "BlockID is ");
2810             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) blockData->blockDataId->id,
2811                            blockData->blockDataId->idLength);
2812
2813             blockData = (CABlockData_t *) u_arraylist_remove(g_context.dataList, i);
2814             if (blockData)
2815             {
2816                 // destroy memory
2817                 CADestroyDataSet(blockData->sentData);
2818                 CADestroyBlockID(blockData->blockDataId);
2819                 OICFree(blockData->payload);
2820                 OICFree(blockData);
2821             }
2822         }
2823     }
2824     oc_mutex_unlock(g_context.blockDataListMutex);
2825     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2826 }