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