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