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 "include/util.h"
17
18 #include <string>
19
20 #include <sys/prctl.h>
21 #include <sys/stat.h>
22 #include <sys/syscall.h>
23 #include <unistd.h>
24
25 #include "parameters.h"
26 #include "securec.h"
27
28 #include "devicestatus_define.h"
29 #include "utility.h"
30
31 #undef LOG_TAG
32 #define LOG_TAG "Util"
33
34 namespace OHOS {
35 namespace Msdp {
36 namespace DeviceStatus {
37 namespace {
38 constexpr size_t BUF_TID_SIZE { 10 };
39 constexpr size_t PROGRAM_NAME_SIZE { 256 };
40 constexpr size_t BUF_CMD_SIZE { 512 };
41 constexpr uint32_t BASE_YEAR { 1900 };
42 constexpr uint32_t BASE_MON { 1 };
43 constexpr uint32_t MS_NS { 1000000 };
44 constexpr int32_t FILE_SIZE_MAX { 0x5000 };
45 constexpr size_t SHORT_KEY_LENGTH { 20 };
46 constexpr size_t PLAINTEXT_LENGTH { 4 };
47 constexpr int32_t ROTATE_POLICY_WINDOW_ROTATE { 0 };
48 constexpr int32_t ROTATE_POLICY_SCREEN_ROTATE { 1 };
49 constexpr int32_t ROTATE_POLICY_FOLD_MODE { 2 };
50 const int32_t ROTATE_POLICY = OHOS::system::GetIntParameter("const.window.device.rotate_policy", 0);
51 const std::string FOLD_ROTATE_POLICY = OHOS::system::GetParameter("const.window.foldabledevice.rotate_policy", "0,0");
52 const std::string SVG_PATH { "/system/etc/device_status/drag_icon/" };
53 } // namespace
54
GetPid()55 int32_t GetPid()
56 {
57 return static_cast<int32_t>(getpid());
58 }
59
GetThisThreadIdOfString()60 static std::string GetThisThreadIdOfString()
61 {
62 thread_local std::string threadLocalId;
63 if (threadLocalId.empty()) {
64 long tid = syscall(SYS_gettid);
65 char buf[BUF_TID_SIZE] = { 0 };
66 const int32_t ret = sprintf_s(buf, BUF_TID_SIZE, "%06d", tid);
67 if (ret < 0) {
68 FI_HILOGE("Call sprintf_s failed, ret:%{public}d", ret);
69 return threadLocalId;
70 }
71 buf[BUF_TID_SIZE - 1] = '\0';
72 threadLocalId = buf;
73 }
74 return threadLocalId;
75 }
76
GetThisThreadId()77 uint64_t GetThisThreadId()
78 {
79 std::string threadId = GetThisThreadIdOfString();
80 uint64_t tid = std::stoull(threadId);
81 return tid;
82 }
83
GetMillisTime()84 int64_t GetMillisTime()
85 {
86 auto timeNow = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now());
87 auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(timeNow.time_since_epoch());
88 return tmp.count();
89 }
90
GetTimeStamp(std::string & startTime)91 void GetTimeStamp(std::string &startTime)
92 {
93 timespec curTime;
94 clock_gettime(CLOCK_REALTIME, &curTime);
95 struct tm *timeinfo = localtime(&(curTime.tv_sec));
96 CHKPV(timeinfo);
97 startTime.append(std::to_string(timeinfo->tm_year + BASE_YEAR)).append("-")
98 .append(std::to_string(timeinfo->tm_mon + BASE_MON)).append("-").append(std::to_string(timeinfo->tm_mday))
99 .append(" ").append(std::to_string(timeinfo->tm_hour)).append(":").append(std::to_string(timeinfo->tm_min))
100 .append(":").append(std::to_string(timeinfo->tm_sec)).append(".")
101 .append(std::to_string(curTime.tv_nsec / MS_NS));
102 }
103
SetThreadName(const std::string & name)104 void SetThreadName(const std::string &name)
105 {
106 prctl(PR_SET_NAME, name.c_str());
107 }
108
StringToken(std::string & strs,const std::string & sep,std::string & token)109 static size_t StringToken(std::string &strs, const std::string &sep, std::string &token)
110 {
111 token = "";
112 if (strs.empty()) {
113 return strs.npos;
114 }
115 size_t seat = strs.npos;
116 size_t temp = 0;
117 for (auto &item : sep) {
118 temp = strs.find(item);
119 if (strs.npos != temp) {
120 seat = (std::min)(seat, temp);
121 }
122 }
123 if (strs.npos != seat) {
124 token = strs.substr(0, seat);
125 if (strs.npos != seat + 1) {
126 strs = strs.substr(seat + 1, strs.npos);
127 }
128 if (seat == 0) {
129 return StringToken(strs, sep, token);
130 }
131 } else {
132 token = strs;
133 strs = "";
134 }
135 return token.size();
136 }
137
StringSplit(const std::string & str,const std::string & sep,std::vector<std::string> & vecList)138 size_t StringSplit(const std::string &str, const std::string &sep, std::vector<std::string> &vecList)
139 {
140 size_t size = 0;
141 auto strs = str;
142 std::string token;
143 while (str.npos != (size = StringToken(strs, sep, token))) {
144 vecList.push_back(token);
145 }
146 return vecList.size();
147 }
148
StringPrintf(const char * format,...)149 std::string StringPrintf(const char *format, ...)
150 {
151 char space[1024] { 0 };
152
153 va_list ap;
154 va_start(ap, format);
155 std::string result;
156 int32_t ret = vsnprintf_s(space, sizeof(space), sizeof(space) - 1, format, ap);
157 if (ret >= RET_OK && static_cast<size_t>(ret) < sizeof(space)) {
158 result = space;
159 } else {
160 FI_HILOGE("The buffer is overflow");
161 }
162 va_end(ap);
163 return result;
164 }
165
GetAnonyString(const std::string & value)166 std::string GetAnonyString(const std::string &value)
167 {
168 if (value.empty()) {
169 return "empty";
170 }
171 std::string anonyStr = "******";
172 std::string str;
173 size_t strLen = value.length();
174 if (strLen == 0) {
175 FI_HILOGE("strLen is 0, value will overflow");
176 return "empty";
177 } else if (strLen <= SHORT_KEY_LENGTH) {
178 str += value[0];
179 str += anonyStr;
180 str += value[strLen - 1];
181 } else {
182 str.append(value, 0, PLAINTEXT_LENGTH);
183 str += anonyStr;
184 str.append(value, strLen - PLAINTEXT_LENGTH, PLAINTEXT_LENGTH);
185 }
186 return str;
187 }
188
GetFileName(const std::string & path)189 static std::string GetFileName(const std::string &path)
190 {
191 size_t nPos = path.find_last_of('/');
192 if (path.npos == nPos) {
193 nPos = path.find_last_of('\\');
194 }
195 if (path.npos == nPos) {
196 return path;
197 }
198 return path.substr(nPos + 1, path.npos);
199 }
200
GetProgramName()201 const char* GetProgramName()
202 {
203 static char programName[PROGRAM_NAME_SIZE] = { 0 };
204 if (programName[0] != '\0') {
205 return programName;
206 }
207
208 char buf[BUF_CMD_SIZE] = { 0 };
209 int32_t ret = sprintf_s(buf, BUF_CMD_SIZE, "/proc/%d/cmdline", static_cast<int32_t>(getpid()));
210 if (ret == -1) {
211 FI_HILOGE("GetProcessInfo sprintf_s cmdline error");
212 return "";
213 }
214 FILE *fp = fopen(buf, "rb");
215 if (fp == nullptr) {
216 FI_HILOGE("The fp is nullptr, filename:%{public}s", buf);
217 return "";
218 }
219 static constexpr size_t bufLineSize = 512;
220 char bufLine[bufLineSize] = { 0 };
221 if ((fgets(bufLine, bufLineSize, fp) == nullptr)) {
222 FI_HILOGE("fgets failed");
223 if (fclose(fp) != 0) {
224 FI_HILOGW("Close file failed");
225 }
226 fp = nullptr;
227 return "";
228 }
229 if (fclose(fp) != 0) {
230 FI_HILOGW("Close file:%{public}s failed", buf);
231 }
232 fp = nullptr;
233
234 std::string tempName(bufLine);
235 tempName = GetFileName(tempName);
236 if (tempName.empty()) {
237 FI_HILOGE("tempName is empty");
238 return "";
239 }
240 size_t copySize = std::min(tempName.size(), PROGRAM_NAME_SIZE - 1);
241 if (copySize == 0) {
242 FI_HILOGE("The copySize is 0");
243 return "";
244 }
245 errno_t result = memcpy_s(programName, PROGRAM_NAME_SIZE, tempName.c_str(), copySize);
246 if (result != EOK) {
247 FI_HILOGE("memcpy_s failed");
248 return "";
249 }
250 FI_HILOGI("Get program name success, programName:%{public}s", programName);
251
252 return programName;
253 }
254
CheckFileExtendName(const std::string & filePath,const std::string & checkExtension)255 bool CheckFileExtendName(const std::string &filePath, const std::string &checkExtension)
256 {
257 std::string::size_type pos = filePath.find_last_of('.');
258 if (pos == std::string::npos) {
259 FI_HILOGE("File is not found extension");
260 return false;
261 }
262 return (filePath.substr(pos + 1, filePath.npos) == checkExtension);
263 }
264
IsValidPath(const std::string & rootDir,const std::string & filePath)265 bool IsValidPath(const std::string &rootDir, const std::string &filePath)
266 {
267 return (filePath.compare(0, rootDir.size(), rootDir) == 0);
268 }
269
IsValidSvgPath(const std::string & filePath)270 bool IsValidSvgPath(const std::string &filePath)
271 {
272 return IsValidPath(SVG_PATH, filePath);
273 }
274
IsValidSvgFile(const std::string & filePath)275 bool IsValidSvgFile(const std::string &filePath)
276 {
277 CALL_DEBUG_ENTER;
278 if (filePath.empty()) {
279 FI_HILOGE("FilePath is empty");
280 return false;
281 }
282 char realPath[PATH_MAX] = { 0 };
283 if (realpath(filePath.c_str(), realPath) == nullptr) {
284 FI_HILOGE("Realpath return nullptr, realPath:%{private}s", realPath);
285 return false;
286 }
287 if (!IsValidSvgPath(realPath)) {
288 FI_HILOGE("File path invalid");
289 return false;
290 }
291 if (!Utility::DoesFileExist(realPath)) {
292 FI_HILOGE("File not exist");
293 return false;
294 }
295 if (!CheckFileExtendName(realPath, "svg")) {
296 FI_HILOGE("Unable to parse files other than svg format");
297 return false;
298 }
299 int32_t fileSize = Utility::GetFileSize(realPath);
300 if ((fileSize <= 0) || (fileSize > FILE_SIZE_MAX)) {
301 FI_HILOGE("File size out of read range");
302 return false;
303 }
304 return true;
305 }
306
IsNum(const std::string & str)307 bool IsNum(const std::string &str)
308 {
309 std::istringstream sin(str);
310 double num = 0.0;
311 return (sin >> num) && sin.eof();
312 }
313
GetRotatePolicy(bool & isScreenRotation,std::vector<std::string> & foldRotatePolicys)314 void GetRotatePolicy(bool &isScreenRotation, std::vector<std::string> &foldRotatePolicys)
315 {
316 if (ROTATE_POLICY == ROTATE_POLICY_WINDOW_ROTATE) {
317 isScreenRotation = false;
318 return;
319 }
320 if (ROTATE_POLICY == ROTATE_POLICY_SCREEN_ROTATE) {
321 isScreenRotation = true;
322 return;
323 }
324 if (ROTATE_POLICY == ROTATE_POLICY_FOLD_MODE) {
325 isScreenRotation = false;
326 StringSplit(FOLD_ROTATE_POLICY, ",", foldRotatePolicys);
327 return;
328 }
329 }
330 } // namespace DeviceStatus
331 } // namespace Msdp
332 } // namespace OHOS