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