• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 "zip_helper.h"
17 
18 #include <algorithm>
19 #include <cerrno>
20 #include <cstdio>
21 #include <cstdlib>
22 #include <cstring>
23 #include <ctime>
24 #include <fcntl.h>
25 #include <regex>
26 #include <sys/ioctl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #include "file_util.h"
31 #include "string_ex.h"
32 #include "securec.h"
33 #include "limits.h"
34 #include "bundle_mgr_client.h"
35 #include "sanitizerd_log.h"
36 #include "parameters.h"
37 
38 namespace OHOS {
39 namespace HiviewDFX {
40 using namespace OHOS::AppExecFwk;
IsLinkFile(const std::string & sfilename)41 bool IsLinkFile(const std::string& sfilename)
42 {
43     struct stat statinfo {};
44     bool isslnk = false;
45 
46     if (lstat(sfilename.c_str(), &statinfo) < 0) {
47         SANITIZERD_LOGE("IsLinkFile lstat %{public}s err: %{public}s", sfilename.c_str(), strerror(errno));
48         return isslnk;
49     }
50 
51     if (!S_ISLNK(statinfo.st_mode) && statinfo.st_nlink > 1) {
52         SANITIZERD_LOGI("IsLinkFile hardlink %{public}s", sfilename.c_str());
53     } else if (S_ISLNK(statinfo.st_mode)) {
54         isslnk = true;
55     }
56     return isslnk;
57 }
58 
GetRealPath(const std::string & fn,std::string & out)59 bool GetRealPath(const std::string& fn, std::string& out)
60 {
61     char buf[SL_BUF_LEN];
62     ssize_t count = readlink(fn.c_str(), buf, sizeof(buf));
63     if (count != -1 && count <= static_cast<ssize_t>(sizeof(buf))) {
64         buf[count] = '\0';
65         out = std::string(buf);
66         return true;
67     }
68     return false;
69 }
70 
ReadFileToString(const std::string & path,std::string & out)71 bool ReadFileToString(const std::string& path, std::string& out)
72 {
73     std::string realfpath;
74     if (IsLinkFile(path)) {
75         GetRealPath(path, realfpath);
76     } else {
77         realfpath = path;
78     }
79     return FileUtil::LoadStringFromFile(path, out);
80 }
81 
SplitString(const std::string & input,const std::string & regex)82 std::vector<std::string> SplitString(const std::string& input, const std::string& regex)
83 {
84     std::regex re(regex);
85     std::sregex_token_iterator first {input.begin(), input.end(), re, -1}, last;
86     return {first, last};
87 }
88 
HashString(const std::string & input)89 unsigned HashString(const std::string& input)
90 {
91     unsigned hash = 0;
92     for (size_t i = 0; i < input.length(); ++i) {
93         hash = hash * HASH_FACTOR + input[i];
94     }
95     return hash;
96 }
97 
IsNameValid(const std::string & name,const std::string & sep,bool canEmpty)98 bool IsNameValid(const std::string& name, const std::string& sep, bool canEmpty)
99 {
100     std::vector<std::string> nameVec;
101     SplitStr(name, sep, nameVec, canEmpty, false);
102     std::regex re("^[a-zA-Z][a-zA-Z0-9_]*$");
103     for (auto const& splitName : nameVec) {
104         if (!std::regex_match(splitName, re)) {
105             SANITIZERD_LOGI("Invalid splitName:%{public}s", splitName.c_str());
106             return false;
107         }
108     }
109     return true;
110 }
111 
IsModuleNameValid(const std::string & name)112 bool IsModuleNameValid(const std::string& name)
113 {
114     if (name.empty() || name.size() > MAX_NAME_LENGTH) {
115         SANITIZERD_LOGI("invalid log name.");
116         return false;
117     }
118 
119     if (name.find("/") != std::string::npos || name.find(".") == std::string::npos) {
120         std::string path = name.substr(1); // may skip first .
121         path.erase(path.find_last_not_of(" \n\r\t") + 1);
122         SANITIZERD_LOGI("module name:%{public}s", name.c_str());
123         return IsNameValid(path, "/", false);
124     }
125 
126     return IsNameValid(name, ".", true);
127 }
128 
GetApplicationNameById(int32_t uid)129 std::string GetApplicationNameById(int32_t uid)
130 {
131     std::string bundleName;
132     AppExecFwk::BundleMgrClient client;
133     if (client.GetNameForUid(uid, bundleName) != ERR_OK) {
134         SANITIZERD_LOGW("Failed to query bundleName from bms, uid:%{public}d.", uid);
135     } else {
136         SANITIZERD_LOGI("bundleName of uid:%{public}d is %{public}s", uid, bundleName.c_str());
137     }
138     return bundleName;
139 }
140 
GetApplicationVersion(int32_t uid,const std::string & bundleName)141 std::string GetApplicationVersion(int32_t uid, const std::string& bundleName)
142 {
143     AppExecFwk::BundleInfo info;
144     AppExecFwk::BundleMgrClient client;
145     if (!client.GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
146                               info, Constants::ALL_USERID)) {
147         SANITIZERD_LOGW("Failed to query BundleInfo from bms, uid:%{public}d.", uid);
148         return "";
149     } else {
150         SANITIZERD_LOGI("The version of %{public}s is %{public}s", bundleName.c_str(),
151                         info.versionName.c_str());
152     }
153     return info.versionName;
154 }
155 
CreateMultiTierDirectory(const std::string & directoryPath,const std::string & rootDirPath,const uid_t dirOwner,const gid_t dirGroup)156 int32_t CreateMultiTierDirectory(const std::string &directoryPath, const std::string &rootDirPath,
157                                  const uid_t dirOwner, const gid_t dirGroup)
158 {
159     int32_t ret = -1;
160     uint32_t dirPathLen = directoryPath.length();
161     if (dirPathLen > PATH_MAX) {
162         return ret;
163     }
164     char tmpDirPath[PATH_MAX] = { 0 };
165     for (uint32_t i = 0; i < dirPathLen; ++i) {
166         tmpDirPath[i] = directoryPath[i];
167         if (i < rootDirPath.length() && directoryPath[i] != rootDirPath[i]) {
168             return ret;
169         } else if (i < rootDirPath.length() || tmpDirPath[i] != '/') {
170             continue;
171         }
172         if (access(tmpDirPath, 0) != 0) {
173             ret = mkdir(tmpDirPath, DEFAULT_LOG_DIR_MODE);
174             ret += chown(tmpDirPath, dirOwner, dirGroup);
175             if (ret != 0) {
176                 SANITIZERD_LOGE("Fail to create dir %{public}s,  err: %{public}s.",
177                                 tmpDirPath, strerror(errno));
178                 return ret;
179             }
180         }
181     }
182     return 0;
183 }
184 
GetCollectedDataSavePath(const T_SANITIZERD_PARAMS * params)185 static std::string GetCollectedDataSavePath(const T_SANITIZERD_PARAMS *params)
186 {
187     std::string faultLogPath = std::string(ROOT_FAULTLOG_LOG_PATH);
188     std::string filePath = std::string(CUSTOM_SANITIZER_LOG_PATH);
189     return filePath;
190 }
191 
CalcCollectedLogName(T_SANITIZERD_PARAMS * params)192 static std::string CalcCollectedLogName(T_SANITIZERD_PARAMS *params)
193 {
194     std::string filePath = GetCollectedDataSavePath(params);
195     if (filePath.size() == 0) {
196         return filePath;
197     }
198     std::string prefix = std::string(SANITIZERD_TYPE_STR[params->type][PREFIXFILENAME]);
199     std::string name = params->procName;
200     if (name.find("/") != std::string::npos) {
201         name = params->procName.substr(params->procName.find_last_of("/") + 1);
202     }
203 
204     std::string fileName = "";
205     fileName.append(prefix);
206     fileName.append("-");
207     fileName.append(name);
208     fileName.append("-");
209     fileName.append(std::to_string(params->uid));
210     fileName.append("-");
211     fileName.append(std::to_string(params->happenTime));
212 
213     std::string fullName = filePath + fileName;
214 
215     params->logName = fileName;
216 
217     return fullName;
218 }
219 
CreateLogFile(const std::string & name)220 static int32_t CreateLogFile(const std::string& name)
221 {
222     int32_t fd = -1;
223     if (!FileUtil::FileExists(name)) {
224         SANITIZERD_LOGW("file %{public}s is creating now.", name.c_str());
225     }
226     fd = open(name.c_str(), O_CREAT | O_WRONLY | O_TRUNC, DEFAULT_LOG_FILE_MODE);
227     return fd;
228 }
229 
WriteNewFile(const int32_t fd,const T_SANITIZERD_PARAMS * params)230 static bool WriteNewFile(const int32_t fd, const T_SANITIZERD_PARAMS *params)
231 {
232     if (fd < 0) {
233         return false;
234     }
235 
236     FileUtil::SaveStringToFd(fd, "Generated by HiviewDFX @OpenHarmony " +
237             system::GetParameter(DEVICE_OHOS_VERSION_PARAM, EMPTY_PARAM) + "\n" +
238             "=================================================================\n" +
239             "TIMESTAMP:" + std::to_string(params->happenTime) + "\n" +
240             "Pid:" + std::to_string(params->pid) + "\n" +
241             "Uid:" + std::to_string(params->uid) + "\n" +
242             "Process name:" + params->procName + "\n" +
243             "Reason:" + std::string(SANITIZERD_TYPE_STR[params->type][ORISANITIZERTYPE]) + ":" +
244             params->errType + "\n" +
245             "Fault thread Info:\n" +
246             params->description);
247 
248     close(fd);
249     return true;
250 }
251 
WriteCollectedData(T_SANITIZERD_PARAMS * params)252 void WriteCollectedData(T_SANITIZERD_PARAMS *params)
253 {
254     std::string fullName = CalcCollectedLogName(params);
255     if (fullName.size() == 0) {
256         return;
257     }
258     int32_t fd = CreateLogFile(fullName);
259     if (fd < 0) {
260         return;
261     }
262 
263     if (!WriteNewFile(fd, params)) {
264         SANITIZERD_LOGE("Fail to write %{public}s,  err: %{public}s.", fullName.c_str(), strerror(errno));
265     }
266 }
267 } // namespace HiviewDFX
268 } // namespace OHOS
269