Imported Upstream version 1.0.1
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / adapter_util / cafragmentation.c
1 /******************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #include <string.h>
22 #include <math.h>
23
24 #include "cacommon.h"
25 #include "caadapterutils.h"
26 #include "cafragmentation.h"
27
28 /**
29  * Debugging tag for fragmentation module.
30  */
31 #define CA_FRAGMENTATION_TAG "CA_FRAGMENTATION"
32
33 CAResult_t CAGenerateHeader(uint8_t *header,
34                             size_t headerLength,
35                             size_t dataLength)
36 {
37     OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "IN");
38
39     VERIFY_NON_NULL(header, CA_FRAGMENTATION_TAG, "header is NULL");
40
41     if (headerLength < CA_HEADER_LENGTH)
42     {
43         return CA_STATUS_FAILED;
44     }
45
46     if (dataLength > MAX_DATA_LENGTH_SUPPORTED)
47     {
48         OIC_LOG_V(WARNING,
49                   CA_FRAGMENTATION_TAG,
50                   "Given length is more than %d.  It will be truncated.",
51                   MAX_DATA_LENGTH_SUPPORTED);
52     }
53
54     // Only bother initializing the header section of the buffer.  It
55     // is up to the caller to handle the data section.
56     memset(header, 0, CA_HEADER_LENGTH);
57
58     // If length is more than 4095 then it will be truncated.
59     header[1] = dataLength & 0xFF;
60     dataLength >>= 8;
61     header[0] = dataLength & 0x0F;
62     header[0] = header[0] | 0x40; // Adding version 0100.
63                                   // (Not used. Future use)
64
65     OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "OUT");
66
67     return CA_STATUS_OK;
68 }
69
70 uint32_t CAParseHeader(const uint8_t *header, size_t length)
71 {
72     OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "IN");
73
74     VERIFY_NON_NULL_RET(header, CA_FRAGMENTATION_TAG, "header is NULL", 0);
75
76     uint32_t dataLen = 0;
77
78     if (length >= CA_HEADER_LENGTH)
79     {
80         dataLen = ((header[0] & 0x0F) << 8) | (header[1] & 0xFF);
81     }
82
83     OIC_LOG(DEBUG, CA_FRAGMENTATION_TAG, "OUT");
84
85     return dataLen;
86 }