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