1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "devicestatus_data_parse.h"
17 
18 #include <fcntl.h>
19 #include <unistd.h>
20 
21 #include <sys/stat.h>
22 
23 #include "devicestatus_data_define.h"
24 #include "devicestatus_errors.h"
25 #include "fi_log.h"
26 #include "json_parser.h"
27 #include "utility.h"
28 
29 #undef LOG_TAG
30 #define LOG_TAG "DeviceStatusDataParse"
31 
32 namespace OHOS {
33 namespace Msdp {
34 namespace DeviceStatus {
35 namespace {
36 constexpr int32_t FILE_SIZE_MAX { 0x5000 };
37 constexpr int32_t READ_DATA_BUFF_SIZE { 256 };
38 const std::string MSDP_DATA_PATH { "/data/msdp/device_status_data.json" };
39 const std::string MSDP_DATA_DIR { "/data/msdp" };
40 } // namespace
41 
42 std::vector<int32_t> DeviceStatusDataParse::tempcount_ =
43     std::vector<int32_t> (static_cast<int32_t>(Type::TYPE_MAX), static_cast<int32_t>(TypeValue::INVALID));
44 
CreateJsonFile()45 int32_t DeviceStatusDataParse::CreateJsonFile()
46 {
47     int32_t fd = open(MSDP_DATA_PATH.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
48     if (fd < 0) {
49         FI_HILOGE("open failed");
50         return DEVICESTATUS_FAILED;
51     }
52     if (close(fd) < 0) {
53         FI_HILOGE("close fd failed, error:%{public}s, fd:%{public}d", strerror(errno), fd);
54     }
55 
56     struct stat buf;
57     if (stat(MSDP_DATA_DIR.c_str(), &buf) != 0) {
58         FI_HILOGE("start folder path is invalid %{public}d", errno);
59         return DEVICESTATUS_FAILED;
60     }
61     if (chown(MSDP_DATA_PATH.c_str(), buf.st_uid, buf.st_gid) != 0) {
62         FI_HILOGE("chown failed, errno:%{public}d", errno);
63         return DEVICESTATUS_FAILED;
64     }
65 
66     return DEVICESTATUS_OK;
67 }
68 
ParseDeviceStatusData(Type type,Data & data)69 bool DeviceStatusDataParse::ParseDeviceStatusData(Type type, Data& data)
70 {
71     std::string jsonBuf = ReadJsonFile(MSDP_DATA_PATH.c_str());
72     if (jsonBuf.empty()) {
73         FI_HILOGE("Read json failed, errno:%{public}d", errno);
74         data.type = type;
75         data.value = OnChangedValue::VALUE_INVALID;
76         return false;
77     }
78     return DeviceStatusDataInit(jsonBuf, true, type, data);
79 }
80 
DeviceStatusDataInit(const std::string & fileData,bool logStatus,Type & type,Data & data)81 bool DeviceStatusDataParse::DeviceStatusDataInit(const std::string& fileData, bool logStatus, Type& type,
82     Data& data)
83 {
84     CALL_DEBUG_ENTER;
85     JsonParser parser;
86     parser.json = cJSON_Parse(fileData.c_str());
87     data.type = type;
88     data.value = OnChangedValue::VALUE_INVALID;
89     if (cJSON_IsArray(parser.json)) {
90         FI_HILOGE("parser is array");
91         return false;
92     }
93 
94     if (type < Type::TYPE_ABSOLUTE_STILL || type >= Type::TYPE_MAX) {
95         FI_HILOGE("type error");
96         return false;
97     }
98 
99     cJSON* mockarray = cJSON_GetObjectItem(parser.json, DeviceStatusJson[type].json.c_str());
100     if (!cJSON_IsArray(mockarray)) {
101         FI_HILOGE("mockarray is not array");
102         return false;
103     }
104     int32_t jsonsize = cJSON_GetArraySize(mockarray);
105     if (jsonsize == 0) {
106         FI_HILOGE("Json size is zero");
107         return false;
108     }
109     tempcount_[type] = tempcount_[type] % jsonsize;
110     cJSON* mockvalue = cJSON_GetArrayItem(mockarray, tempcount_[type]);
111     tempcount_[type]++;
112     data.type = type;
113     if (mockvalue == nullptr || !cJSON_IsNumber(mockvalue)) {
114         FI_HILOGE("Json parser number is failed");
115         return false;
116     }
117     data.value = static_cast<OnChangedValue>(mockvalue->valueint);
118     FI_HILOGD("type:%{public}d, status:%{public}d", data.type, data.value);
119     return true;
120 }
121 
DisableCount(const Type type)122 bool DeviceStatusDataParse::DisableCount(const Type type)
123 {
124     CALL_DEBUG_ENTER;
125     if (tempcount_.size() <= static_cast<size_t>(type)) {
126         FI_HILOGE("The index is out of bounds, size is %{public}zu", tempcount_.size());
127         return false;
128     }
129     tempcount_[static_cast<int32_t>(type)] = static_cast<int32_t>(TypeValue::INVALID);
130     return true;
131 }
132 
ReadJsonFile(const std::string & filePath)133 std::string DeviceStatusDataParse::ReadJsonFile(const std::string &filePath)
134 {
135     if (filePath.empty()) {
136         FI_HILOGE("Path is empty");
137         return {};
138     }
139     char realPath[PATH_MAX] = { 0 };
140     if (realpath(filePath.c_str(), realPath) == nullptr) {
141         FI_HILOGE("Path is error, %{public}d", errno);
142         return {};
143     }
144     if (!CheckFileDir(realPath, MSDP_DATA_DIR)) {
145         FI_HILOGE("File dir is invalid");
146         return {};
147     }
148     if (!CheckFileExtendName(realPath, "json")) {
149         FI_HILOGE("Unable to parse files other than json format");
150         return {};
151     }
152     if (!Utility::DoesFileExist(filePath.c_str())) {
153         FI_HILOGE("File not exist");
154         return {};
155     }
156     if (!CheckFileSize(filePath)) {
157         FI_HILOGE("File size out of read range");
158         return {};
159     }
160     return ReadFile(realPath);
161 }
162 
CheckFileDir(const std::string & filePath,const std::string & dir)163 bool DeviceStatusDataParse::CheckFileDir(const std::string& filePath, const std::string& dir)
164 {
165     if (filePath.compare(0, MSDP_DATA_DIR.size(), MSDP_DATA_DIR) != 0) {
166         FI_HILOGE("FilePath dir is invalid");
167         return false;
168     }
169     return true;
170 }
171 
CheckFileSize(const std::string & filePath)172 bool DeviceStatusDataParse::CheckFileSize(const std::string& filePath)
173 {
174     int32_t fileSize = Utility::GetFileSize(filePath);
175     if ((fileSize <= 0) || (fileSize > FILE_SIZE_MAX)) {
176         FI_HILOGE("File size out of read range");
177         return false;
178     }
179     return true;
180 }
181 
CheckFileExtendName(const std::string & filePath,const std::string & checkExtension)182 bool DeviceStatusDataParse::CheckFileExtendName(const std::string& filePath, const std::string& checkExtension)
183 {
184     std::string::size_type pos = filePath.find_last_of('.');
185     if (pos == std::string::npos) {
186         FI_HILOGE("File is not find extension");
187         return false;
188     }
189     return (filePath.substr(pos + 1, filePath.npos) == checkExtension);
190 }
191 
ReadFile(const std::string & filePath)192 std::string DeviceStatusDataParse::ReadFile(const std::string &filePath)
193 {
194     CALL_DEBUG_ENTER;
195     FILE* fp = fopen(filePath.c_str(), "r");
196     if (fp == nullptr) {
197         FI_HILOGE("Open failed");
198         return {};
199     }
200     std::string dataStr;
201     char buf[READ_DATA_BUFF_SIZE] = { 0 };
202     while (fgets(buf, sizeof(buf), fp) != nullptr) {
203         dataStr += buf;
204     }
205     if (fclose(fp) != 0) {
206         FI_HILOGW("Close file failed");
207     }
208     return dataStr;
209 }
210 } // namespace DeviceStatus
211 } // namespace Msdp
212 } // namespace OHOS
213