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