1 /*
2 * Copyright (c) 2021-2024 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 "bundle_util.h"
17
18 #include <cinttypes>
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <fstream>
22 #include <sstream>
23 #include <sys/sendfile.h>
24 #include <sys/statfs.h>
25
26 #include "bundle_service_constants.h"
27 #ifdef CONFIG_POLOCY_ENABLE
28 #include "config_policy_utils.h"
29 #endif
30 #include "directory_ex.h"
31 #include "hitrace_meter.h"
32 #include "installd_client.h"
33 #include "ipc_skeleton.h"
34 #include "parameter.h"
35 #include "string_ex.h"
36 #ifdef BUNDLE_FRAMEWORK_UDMF_ENABLED
37 #include "type_descriptor.h"
38 #include "utd_client.h"
39 #endif
40
41 namespace OHOS {
42 namespace AppExecFwk {
43 namespace {
44 const std::string::size_type EXPECT_SPLIT_SIZE = 2;
45 constexpr char UUID_SEPARATOR = '-';
46 constexpr size_t ORIGIN_STRING_LENGTH = 32;
47 const std::vector<int32_t> SEPARATOR_POSITIONS { 8, 13, 18, 23};
48 constexpr int64_t HALF_GB = 1024 * 1024 * 512; // 0.5GB
49 constexpr int8_t SPACE_NEED_DOUBLE = 2;
50 constexpr uint16_t UUID_LENGTH_MAX = 512;
51 static std::string g_deviceUdid;
52 static std::mutex g_mutex;
53 // hmdfs and sharefs config
54 constexpr const char* BUNDLE_ID_FILE = "appid";
55 // single max hap size
56 constexpr int64_t ONE_GB = 1024 * 1024 * 1024;
57 constexpr int64_t MAX_HAP_SIZE = ONE_GB * 4; // 4GB
58 constexpr const char* ABC_FILE_PATH = "abc_files";
59 constexpr const char* PGO_FILE_PATH = "pgo_files";
60 #ifdef CONFIG_POLOCY_ENABLE
61 const char* NO_DISABLING_CONFIG_PATH = "/etc/ability_runtime/resident_process_in_extreme_memory.json";
62 #endif
63 const char* NO_DISABLING_CONFIG_PATH_DEFAULT =
64 "/system/etc/ability_runtime/resident_process_in_extreme_memory.json";
65 const std::string EMPTY_STRING = "";
66 constexpr int64_t DISK_REMAINING_SIZE_LIMIT = 1024 * 1024 * 10; // 10M
67 }
68
69 std::mutex BundleUtil::g_mutex;
70
CheckFilePath(const std::string &bundlePath, std::string &realPath)71 ErrCode BundleUtil::CheckFilePath(const std::string &bundlePath, std::string &realPath)
72 {
73 if (!CheckFileName(bundlePath)) {
74 APP_LOGE("bundle file path invalid");
75 return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
76 }
77 if (!CheckFileType(bundlePath, ServiceConstants::INSTALL_FILE_SUFFIX) &&
78 !CheckFileType(bundlePath, ServiceConstants::HSP_FILE_SUFFIX) &&
79 !CheckFileType(bundlePath, ServiceConstants::QUICK_FIX_FILE_SUFFIX) &&
80 !CheckFileType(bundlePath, ServiceConstants::CODE_SIGNATURE_FILE_SUFFIX)) {
81 APP_LOGE("file is not hap, hsp, hqf or sig");
82 return ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME;
83 }
84 if (!PathToRealPath(bundlePath, realPath)) {
85 APP_LOGE("file is not real path");
86 return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
87 }
88 if (access(realPath.c_str(), F_OK) != 0) {
89 APP_LOGE("not access the bundle file path: %{public}s, errno:%{public}d", realPath.c_str(), errno);
90 return ERR_APPEXECFWK_INSTALL_INVALID_BUNDLE_FILE;
91 }
92 if (!CheckFileSize(realPath, MAX_HAP_SIZE)) {
93 APP_LOGE("file size larger than max hap size Max size is: %{public}" PRId64, MAX_HAP_SIZE);
94 return ERR_APPEXECFWK_INSTALL_INVALID_HAP_SIZE;
95 }
96 return ERR_OK;
97 }
98
CheckFilePath(const std::vector<std::string> &bundlePaths, std::vector<std::string> &realPaths)99 ErrCode BundleUtil::CheckFilePath(const std::vector<std::string> &bundlePaths, std::vector<std::string> &realPaths)
100 {
101 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
102 // there are three cases for bundlePaths:
103 // 1. one bundle direction in the bundlePaths, some hap files under this bundle direction.
104 // 2. one hap direction in the bundlePaths.
105 // 3. some hap file directions in the bundlePaths.
106 APP_LOGD("check file path");
107 if (bundlePaths.empty()) {
108 APP_LOGE("bundle file paths invalid");
109 return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
110 }
111 ErrCode ret = ERR_OK;
112
113 if (bundlePaths.size() == 1) {
114 struct stat s;
115 std::string bundlePath = bundlePaths.front();
116 if (stat(bundlePath.c_str(), &s) == 0) {
117 std::string realPath = "";
118 // it is a direction
119 if ((s.st_mode & S_IFDIR) && !GetHapFilesFromBundlePath(bundlePath, realPaths)) {
120 APP_LOGE("GetHapFilesFromBundlePath failed with bundlePath:%{public}s", bundlePaths.front().c_str());
121 return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
122 }
123 // it is a file
124 if ((s.st_mode & S_IFREG) && (ret = CheckFilePath(bundlePaths.front(), realPath)) == ERR_OK) {
125 realPaths.emplace_back(realPath);
126 }
127 return ret;
128 } else {
129 APP_LOGE("bundlePath not existed with :%{public}s", bundlePaths.front().c_str());
130 return ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID;
131 }
132 } else {
133 for (const std::string& bundlePath : bundlePaths) {
134 std::string realPath = "";
135 ret = CheckFilePath(bundlePath, realPath);
136 if (ret != ERR_OK) {
137 return ret;
138 }
139 realPaths.emplace_back(realPath);
140 }
141 }
142 APP_LOGD("finish check file path");
143 return ret;
144 }
145
CheckFileType(const std::string &fileName, const std::string &extensionName)146 bool BundleUtil::CheckFileType(const std::string &fileName, const std::string &extensionName)
147 {
148 APP_LOGD("path is %{public}s, support suffix is %{public}s", fileName.c_str(), extensionName.c_str());
149 if (!CheckFileName(fileName)) {
150 return false;
151 }
152
153 auto position = fileName.rfind('.');
154 if (position == std::string::npos) {
155 APP_LOGE("filename no extension name");
156 return false;
157 }
158
159 std::string suffixStr = fileName.substr(position);
160 return LowerStr(suffixStr) == extensionName;
161 }
162
CheckFileName(const std::string &fileName)163 bool BundleUtil::CheckFileName(const std::string &fileName)
164 {
165 if (fileName.empty()) {
166 APP_LOGE("the file name is empty");
167 return false;
168 }
169 if (fileName.size() > ServiceConstants::PATH_MAX_SIZE) {
170 APP_LOGE("bundle file path length %{public}zu too long", fileName.size());
171 return false;
172 }
173 return true;
174 }
175
CheckFileSize(const std::string &bundlePath, const int64_t fileSize)176 bool BundleUtil::CheckFileSize(const std::string &bundlePath, const int64_t fileSize)
177 {
178 APP_LOGD("fileSize is %{public}" PRId64, fileSize);
179 struct stat fileInfo = { 0 };
180 if (stat(bundlePath.c_str(), &fileInfo) != 0) {
181 APP_LOGE("call stat error:%{public}d", errno);
182 return false;
183 }
184 if (fileInfo.st_size > fileSize) {
185 return false;
186 }
187 return true;
188 }
189
CheckSystemSize(const std::string &bundlePath, const std::string &diskPath)190 bool BundleUtil::CheckSystemSize(const std::string &bundlePath, const std::string &diskPath)
191 {
192 struct statfs diskInfo = { 0 };
193 if (statfs(diskPath.c_str(), &diskInfo) != 0) {
194 APP_LOGE("call statfs error:%{public}d", errno);
195 return false;
196 }
197 int64_t freeSize = static_cast<int64_t>(diskInfo.f_bavail * diskInfo.f_bsize);
198 APP_LOGD("left free size in the disk path is %{public}" PRId64, freeSize);
199 struct stat fileInfo = { 0 };
200 if (stat(bundlePath.c_str(), &fileInfo) != 0) {
201 APP_LOGE("call stat error:%{public}d", errno);
202 return false;
203 }
204 if (std::max(fileInfo.st_size * SPACE_NEED_DOUBLE, HALF_GB) > freeSize) {
205 return false;
206 }
207 return true;
208 }
209
CheckSystemFreeSize(const std::string &path, int64_t size)210 bool BundleUtil::CheckSystemFreeSize(const std::string &path, int64_t size)
211 {
212 struct statfs diskInfo = { 0 };
213 if (statfs(path.c_str(), &diskInfo) != 0) {
214 APP_LOGE("call statfs error:%{public}d", errno);
215 return false;
216 }
217 int64_t freeSize = static_cast<int64_t>(diskInfo.f_bavail * diskInfo.f_bsize);
218 return freeSize >= size;
219 }
220
CheckSystemSizeAndHisysEvent(const std::string &path, const std::string &fileName)221 bool BundleUtil::CheckSystemSizeAndHisysEvent(const std::string &path, const std::string &fileName)
222 {
223 struct statfs diskInfo = { 0 };
224 if (statfs(path.c_str(), &diskInfo) != 0) {
225 APP_LOGE("call statfs error:%{public}d", errno);
226 return false;
227 }
228 int64_t freeSize = static_cast<int64_t>(diskInfo.f_bavail * diskInfo.f_bsize);
229 return freeSize < DISK_REMAINING_SIZE_LIMIT;
230 }
231
GetHapFilesFromBundlePath(const std::string& currentBundlePath, std::vector<std::string>& hapFileList)232 bool BundleUtil::GetHapFilesFromBundlePath(const std::string& currentBundlePath, std::vector<std::string>& hapFileList)
233 {
234 APP_LOGD("GetHapFilesFromBundlePath with path is %{public}s", currentBundlePath.c_str());
235 if (currentBundlePath.empty()) {
236 return false;
237 }
238 DIR* dir = opendir(currentBundlePath.c_str());
239 if (dir == nullptr) {
240 char errMsg[256] = {0};
241 strerror_r(errno, errMsg, sizeof(errMsg));
242 APP_LOGE("GetHapFilesFromBundlePath open bundle dir:%{public}s failed due to %{public}s, errno:%{public}d",
243 currentBundlePath.c_str(), errMsg, errno);
244 return false;
245 }
246 std::string bundlePath = currentBundlePath;
247 if (bundlePath.back() != ServiceConstants::FILE_SEPARATOR_CHAR) {
248 bundlePath.append(ServiceConstants::PATH_SEPARATOR);
249 }
250 struct dirent *entry = nullptr;
251 while ((entry = readdir(dir)) != nullptr) {
252 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
253 continue;
254 }
255 const std::string hapFilePath = bundlePath + entry->d_name;
256 std::string realPath = "";
257 if (CheckFilePath(hapFilePath, realPath) != ERR_OK) {
258 APP_LOGE("find invalid hap path %{public}s", hapFilePath.c_str());
259 closedir(dir);
260 return false;
261 }
262 hapFileList.emplace_back(realPath);
263 APP_LOGD("find hap path %{public}s", realPath.c_str());
264
265 if (!hapFileList.empty() && (hapFileList.size() > ServiceConstants::MAX_HAP_NUMBER)) {
266 APP_LOGE("reach the max hap number 128, stop to add more");
267 closedir(dir);
268 return false;
269 }
270 }
271 APP_LOGI("hap number: %{public}zu", hapFileList.size());
272 closedir(dir);
273 return true;
274 }
275
GetCurrentTime()276 int64_t BundleUtil::GetCurrentTime()
277 {
278 int64_t time =
279 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch())
280 .count();
281 APP_LOGD("the current time in seconds is %{public}" PRId64, time);
282 return time;
283 }
284
GetCurrentTimeMs()285 int64_t BundleUtil::GetCurrentTimeMs()
286 {
287 int64_t time =
288 std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())
289 .count();
290 APP_LOGD("the current time in milliseconds is %{public}" PRId64, time);
291 return time;
292 }
293
GetCurrentTimeNs()294 int64_t BundleUtil::GetCurrentTimeNs()
295 {
296 int64_t time =
297 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch())
298 .count();
299 APP_LOGD("the current time in nanoseconds is %{public}" PRId64, time);
300 return time;
301 }
302
DeviceAndNameToKey( const std::string &deviceId, const std::string &bundleName, std::string &key)303 void BundleUtil::DeviceAndNameToKey(
304 const std::string &deviceId, const std::string &bundleName, std::string &key)
305 {
306 key.append(deviceId);
307 key.append(Constants::FILE_UNDERLINE);
308 key.append(bundleName);
309 APP_LOGD("bundleName = %{public}s", bundleName.c_str());
310 }
311
KeyToDeviceAndName( const std::string &key, std::string &deviceId, std::string &bundleName)312 bool BundleUtil::KeyToDeviceAndName(
313 const std::string &key, std::string &deviceId, std::string &bundleName)
314 {
315 bool ret = false;
316 std::vector<std::string> splitStrs;
317 OHOS::SplitStr(key, Constants::FILE_UNDERLINE, splitStrs);
318 // the expect split size should be 2.
319 // key rule is <deviceId>_<bundleName>
320 if (splitStrs.size() == EXPECT_SPLIT_SIZE) {
321 deviceId = splitStrs[0];
322 bundleName = splitStrs[1];
323 ret = true;
324 }
325 APP_LOGD("bundleName = %{public}s", bundleName.c_str());
326 return ret;
327 }
328
GetUserIdByCallingUid()329 int32_t BundleUtil::GetUserIdByCallingUid()
330 {
331 int32_t uid = IPCSkeleton::GetCallingUid();
332 APP_LOGD("get calling uid(%{public}d)", uid);
333 return GetUserIdByUid(uid);
334 }
335
GetUserIdByUid(int32_t uid)336 int32_t BundleUtil::GetUserIdByUid(int32_t uid)
337 {
338 if (uid <= Constants::INVALID_UID) {
339 APP_LOGE("uid illegal: %{public}d", uid);
340 return Constants::INVALID_USERID;
341 }
342
343 return uid / Constants::BASE_USER_RANGE;
344 }
345
MakeFsConfig(const std::string &bundleName, int32_t bundleId, const std::string &configPath)346 void BundleUtil::MakeFsConfig(const std::string &bundleName, int32_t bundleId, const std::string &configPath)
347 {
348 std::string bundleDir = configPath + ServiceConstants::PATH_SEPARATOR + bundleName;
349 if (access(bundleDir.c_str(), F_OK) != 0) {
350 APP_LOGD("fail to access error:%{public}d", errno);
351 if (mkdir(bundleDir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
352 APP_LOGE("make bundle dir error:%{public}d", errno);
353 return;
354 }
355 }
356
357 std::string realBundleDir;
358 if (!PathToRealPath(bundleDir, realBundleDir)) {
359 APP_LOGE("bundleIdFile is not real path");
360 return;
361 }
362
363 realBundleDir += (std::string(ServiceConstants::PATH_SEPARATOR) + BUNDLE_ID_FILE);
364
365 int32_t bundleIdFd = open(realBundleDir.c_str(), O_WRONLY | O_TRUNC);
366 if (bundleIdFd > 0) {
367 std::string bundleIdStr = std::to_string(bundleId);
368 if (write(bundleIdFd, bundleIdStr.c_str(), bundleIdStr.size()) < 0) {
369 APP_LOGE("write bundleId error:%{public}d", errno);
370 }
371 }
372 close(bundleIdFd);
373 }
374
RemoveFsConfig(const std::string &bundleName, const std::string &configPath)375 void BundleUtil::RemoveFsConfig(const std::string &bundleName, const std::string &configPath)
376 {
377 std::string bundleDir = configPath + ServiceConstants::PATH_SEPARATOR + bundleName;
378 std::string realBundleDir;
379 if (!PathToRealPath(bundleDir, realBundleDir)) {
380 APP_LOGE("bundleDir is not real path");
381 return;
382 }
383 if (rmdir(realBundleDir.c_str()) != 0) {
384 APP_LOGE("remove hmdfs bundle dir error:%{public}d", errno);
385 }
386 }
387
CreateTempDir(const std::string &tempDir)388 std::string BundleUtil::CreateTempDir(const std::string &tempDir)
389 {
390 if (!OHOS::ForceCreateDirectory(tempDir)) {
391 APP_LOGE("mkdir %{public}s failed", tempDir.c_str());
392 return "";
393 }
394 if (chown(tempDir.c_str(), Constants::FOUNDATION_UID, ServiceConstants::BMS_GID) != 0) {
395 APP_LOGE("fail to change %{public}s ownership errno:%{public}d", tempDir.c_str(), errno);
396 return "";
397 }
398 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
399 if (!OHOS::ChangeModeFile(tempDir, mode)) {
400 APP_LOGE("change mode failed, temp install dir : %{public}s", tempDir.c_str());
401 return "";
402 }
403 return tempDir;
404 }
405
CreateInstallTempDir(uint32_t installerId, const DirType &type)406 std::string BundleUtil::CreateInstallTempDir(uint32_t installerId, const DirType &type)
407 {
408 std::time_t curTime = std::time(0);
409 std::string tempDir = ServiceConstants::HAP_COPY_PATH;
410 std::string pathseparator = ServiceConstants::PATH_SEPARATOR;
411 if (type == DirType::STREAM_INSTALL_DIR) {
412 tempDir += pathseparator + ServiceConstants::STREAM_INSTALL_PATH;
413 } else if (type == DirType::QUICK_FIX_DIR) {
414 tempDir += pathseparator + ServiceConstants::QUICK_FIX_PATH;
415 } else if (type == DirType::SIG_FILE_DIR) {
416 tempDir += pathseparator + ServiceConstants::SIGNATURE_FILE_PATH;
417 } else if (type == DirType::PGO_FILE_DIR) {
418 tempDir += pathseparator + PGO_FILE_PATH;
419 } else if (type == DirType::ABC_FILE_DIR) {
420 tempDir += pathseparator + ABC_FILE_PATH;
421 } else if (type == DirType::EXT_RESOURCE_FILE_DIR) {
422 tempDir += pathseparator + ServiceConstants::EXT_RESOURCE_FILE_PATH;
423 } else {
424 return "";
425 }
426
427 if (CreateTempDir(tempDir).empty()) {
428 APP_LOGE("create tempDir failed");
429 return "";
430 }
431
432 tempDir += ServiceConstants::PATH_SEPARATOR + std::to_string(curTime) +
433 std::to_string(installerId) + ServiceConstants::PATH_SEPARATOR;
434 return CreateTempDir(tempDir);
435 }
436
CreateSharedBundleTempDir(uint32_t installerId, uint32_t index)437 std::string BundleUtil::CreateSharedBundleTempDir(uint32_t installerId, uint32_t index)
438 {
439 std::time_t curTime = std::time(0);
440 std::string tempDir = ServiceConstants::HAP_COPY_PATH;
441 tempDir += std::string(ServiceConstants::PATH_SEPARATOR) + ServiceConstants::STREAM_INSTALL_PATH;
442 tempDir += ServiceConstants::PATH_SEPARATOR + std::to_string(curTime) + std::to_string(installerId)
443 + Constants::FILE_UNDERLINE + std::to_string(index)+ ServiceConstants::PATH_SEPARATOR;
444 return CreateTempDir(tempDir);
445 }
446
CreateFileDescriptor(const std::string &bundlePath, long long offset)447 int32_t BundleUtil::CreateFileDescriptor(const std::string &bundlePath, long long offset)
448 {
449 int fd = -1;
450 if (bundlePath.length() > ServiceConstants::PATH_MAX_SIZE) {
451 APP_LOGE("the length of the bundlePath exceeds maximum limitation");
452 return fd;
453 }
454 if ((fd = open(bundlePath.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)) < 0) {
455 APP_LOGE("open bundlePath %{public}s failed errno:%{public}d", bundlePath.c_str(), errno);
456 return fd;
457 }
458 if (offset > 0) {
459 lseek(fd, offset, SEEK_SET);
460 }
461 return fd;
462 }
463
CreateFileDescriptorForReadOnly(const std::string &bundlePath, long long offset)464 int32_t BundleUtil::CreateFileDescriptorForReadOnly(const std::string &bundlePath, long long offset)
465 {
466 int fd = -1;
467 if (bundlePath.length() > ServiceConstants::PATH_MAX_SIZE) {
468 APP_LOGE("the length of the bundlePath exceeds maximum limitation");
469 return fd;
470 }
471 std::string realPath;
472 if (!PathToRealPath(bundlePath, realPath)) {
473 APP_LOGE("file is not real path");
474 return fd;
475 }
476
477 if ((fd = open(realPath.c_str(), O_RDONLY)) < 0) {
478 APP_LOGE("open bundlePath %{public}s failed errno:%{public}d", realPath.c_str(), errno);
479 return fd;
480 }
481 if (offset > 0) {
482 lseek(fd, offset, SEEK_SET);
483 }
484 return fd;
485 }
486
CloseFileDescriptor(std::vector<int32_t> &fdVec)487 void BundleUtil::CloseFileDescriptor(std::vector<int32_t> &fdVec)
488 {
489 for_each(fdVec.begin(), fdVec.end(), [](const auto &fd) {
490 if (fd > 0) {
491 close(fd);
492 }
493 });
494 fdVec.clear();
495 }
496
IsExistFile(const std::string &path)497 bool BundleUtil::IsExistFile(const std::string &path)
498 {
499 if (path.empty()) {
500 return false;
501 }
502
503 struct stat buf = {};
504 if (stat(path.c_str(), &buf) != 0) {
505 APP_LOGE("fail stat errno:%{public}d", errno);
506 return false;
507 }
508
509 return S_ISREG(buf.st_mode);
510 }
511
IsExistFileNoLog(const std::string &path)512 bool BundleUtil::IsExistFileNoLog(const std::string &path)
513 {
514 if (path.empty()) {
515 return false;
516 }
517
518 struct stat buf = {};
519 if (stat(path.c_str(), &buf) != 0) {
520 return false;
521 }
522
523 return S_ISREG(buf.st_mode);
524 }
525
IsExistDir(const std::string &path)526 bool BundleUtil::IsExistDir(const std::string &path)
527 {
528 if (path.empty()) {
529 return false;
530 }
531
532 struct stat buf = {};
533 if (stat(path.c_str(), &buf) != 0) {
534 APP_LOGE("fail stat errno:%{public}d", errno);
535 return false;
536 }
537
538 return S_ISDIR(buf.st_mode);
539 }
540
IsExistDirNoLog(const std::string &path)541 bool BundleUtil::IsExistDirNoLog(const std::string &path)
542 {
543 if (path.empty()) {
544 return false;
545 }
546
547 struct stat buf = {};
548 if (stat(path.c_str(), &buf) != 0) {
549 return false;
550 }
551
552 return S_ISDIR(buf.st_mode);
553 }
554
CalculateFileSize(const std::string &bundlePath)555 int64_t BundleUtil::CalculateFileSize(const std::string &bundlePath)
556 {
557 struct stat fileInfo = { 0 };
558 if (stat(bundlePath.c_str(), &fileInfo) != 0) {
559 APP_LOGE("call stat error:%{public}d", errno);
560 return 0;
561 }
562
563 return static_cast<int64_t>(fileInfo.st_size);
564 }
565
RenameFile(const std::string &oldPath, const std::string &newPath)566 bool BundleUtil::RenameFile(const std::string &oldPath, const std::string &newPath)
567 {
568 if (oldPath.empty() || newPath.empty()) {
569 APP_LOGE("oldPath or newPath is empty");
570 return false;
571 }
572
573 if (!DeleteDir(newPath)) {
574 APP_LOGE("delete newPath failed");
575 return false;
576 }
577
578 return rename(oldPath.c_str(), newPath.c_str()) == 0;
579 }
580
DeleteDir(const std::string &path)581 bool BundleUtil::DeleteDir(const std::string &path)
582 {
583 if (IsExistFile(path)) {
584 return OHOS::RemoveFile(path);
585 }
586
587 if (IsExistDir(path)) {
588 return OHOS::ForceRemoveDirectory(path);
589 }
590
591 return true;
592 }
593
IsUtd(const std::string ¶m)594 bool BundleUtil::IsUtd(const std::string ¶m)
595 {
596 #ifdef BUNDLE_FRAMEWORK_UDMF_ENABLED
597 bool isUtd = false;
598 auto ret = UDMF::UtdClient::GetInstance().IsUtd(param, isUtd);
599 return ret == ERR_OK && isUtd;
600 #else
601 return false;
602 #endif
603 }
604
IsSpecificUtd(const std::string ¶m)605 bool BundleUtil::IsSpecificUtd(const std::string ¶m)
606 {
607 if (!IsUtd(param)) {
608 return false;
609 }
610 #ifdef BUNDLE_FRAMEWORK_UDMF_ENABLED
611 std::shared_ptr<UDMF::TypeDescriptor> typeDescriptor;
612 auto ret = UDMF::UtdClient::GetInstance().GetTypeDescriptor(param, typeDescriptor);
613 if (ret != ERR_OK || typeDescriptor == nullptr) {
614 return false;
615 }
616 std::vector<std::string> mimeTypes = typeDescriptor->GetMimeTypes();
617 std::vector<std::string> filenameExtensions = typeDescriptor->GetFilenameExtensions();
618 return !mimeTypes.empty() || !filenameExtensions.empty();
619 #else
620 return false;
621 #endif
622 }
623
GetUtdVectorByMimeType(const std::string &mimeType)624 std::vector<std::string> BundleUtil::GetUtdVectorByMimeType(const std::string &mimeType)
625 {
626 #ifdef BUNDLE_FRAMEWORK_UDMF_ENABLED
627 std::vector<std::string> utdVector;
628 auto ret = UDMF::UtdClient::GetInstance().GetUniformDataTypesByMIMEType(mimeType, utdVector);
629 if (ret != ERR_OK || utdVector.empty()) {
630 return {};
631 }
632 return utdVector;
633 #else
634 return {};
635 #endif
636 }
637
GetBoolStrVal(bool val)638 std::string BundleUtil::GetBoolStrVal(bool val)
639 {
640 return val ? "true" : "false";
641 }
642
CopyFile( const std::string &sourceFile, const std::string &destinationFile)643 bool BundleUtil::CopyFile(
644 const std::string &sourceFile, const std::string &destinationFile)
645 {
646 if (sourceFile.empty() || destinationFile.empty()) {
647 APP_LOGE("Copy file failed due to sourceFile or destinationFile is empty");
648 return false;
649 }
650
651 std::ifstream in(sourceFile);
652 if (!in.is_open()) {
653 APP_LOGE("Copy file failed due to open sourceFile failed errno:%{public}d", errno);
654 return false;
655 }
656
657 std::ofstream out(destinationFile);
658 if (!out.is_open()) {
659 APP_LOGE("Copy file failed due to open destinationFile failed errno:%{public}d", errno);
660 in.close();
661 return false;
662 }
663
664 out << in.rdbuf();
665 in.close();
666 out.close();
667 return true;
668 }
669
CopyFileFast(const std::string &sourcePath, const std::string &destPath)670 bool BundleUtil::CopyFileFast(const std::string &sourcePath, const std::string &destPath)
671 {
672 APP_LOGI("sourcePath : %{public}s, destPath : %{public}s", sourcePath.c_str(), destPath.c_str());
673 if (sourcePath.empty() || destPath.empty()) {
674 APP_LOGE("invalid path");
675 return false;
676 }
677
678 int32_t sourceFd = open(sourcePath.c_str(), O_RDONLY);
679 if (sourceFd == -1) {
680 APP_LOGE("sourcePath open failed, errno : %{public}d", errno);
681 return CopyFile(sourcePath, destPath);
682 }
683
684 struct stat sourceStat;
685 if (fstat(sourceFd, &sourceStat) == -1) {
686 APP_LOGE("fstat failed, errno : %{public}d", errno);
687 close(sourceFd);
688 return CopyFile(sourcePath, destPath);
689 }
690 if (sourceStat.st_size < 0) {
691 APP_LOGE("invalid st_size");
692 close(sourceFd);
693 return CopyFile(sourcePath, destPath);
694 }
695
696 int32_t destFd = open(
697 destPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
698 if (destFd == -1) {
699 APP_LOGE("destPath open failed, errno : %{public}d", errno);
700 close(sourceFd);
701 return CopyFile(sourcePath, destPath);
702 }
703
704 size_t buffer = 524288; // 0.5M
705 size_t transferCount = 0;
706 ssize_t singleTransfer = 0;
707 while ((singleTransfer = sendfile(destFd, sourceFd, nullptr, buffer)) > 0) {
708 transferCount += static_cast<size_t>(singleTransfer);
709 }
710
711 if (singleTransfer == -1 || transferCount != static_cast<size_t>(sourceStat.st_size)) {
712 APP_LOGE("sendfile failed, errno : %{public}d, send count : %{public}zu , file size : %{public}zu",
713 errno, transferCount, static_cast<size_t>(sourceStat.st_size));
714 close(sourceFd);
715 close(destFd);
716 return CopyFile(sourcePath, destPath);
717 }
718
719 close(sourceFd);
720 close(destFd);
721 APP_LOGD("sendfile success");
722 return true;
723 }
724
GetResource(const std::string &bundleName, const std::string &moduleName, uint32_t resId)725 Resource BundleUtil::GetResource(const std::string &bundleName, const std::string &moduleName, uint32_t resId)
726 {
727 Resource resource;
728 resource.bundleName = bundleName;
729 resource.moduleName = moduleName;
730 resource.id = resId;
731 return resource;
732 }
733
CreateDir(const std::string &dir)734 bool BundleUtil::CreateDir(const std::string &dir)
735 {
736 if (dir.empty()) {
737 APP_LOGE("path is empty");
738 return false;
739 }
740
741 if (IsExistFile(dir)) {
742 return true;
743 }
744
745 if (!OHOS::ForceCreateDirectory(dir)) {
746 APP_LOGE("mkdir %{public}s failed", dir.c_str());
747 return false;
748 }
749
750 if (chown(dir.c_str(), Constants::FOUNDATION_UID, ServiceConstants::BMS_GID) != 0) {
751 APP_LOGE("fail change %{public}s ownership, errno:%{public}d", dir.c_str(), errno);
752 return false;
753 }
754
755 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
756 if (!OHOS::ChangeModeFile(dir, mode)) {
757 APP_LOGE("change mode failed, temp install dir : %{public}s", dir.c_str());
758 return false;
759 }
760 return true;
761 }
762
RevertToRealPath(const std::string &sandBoxPath, const std::string &bundleName, std::string &realPath)763 bool BundleUtil::RevertToRealPath(const std::string &sandBoxPath, const std::string &bundleName, std::string &realPath)
764 {
765 if (sandBoxPath.empty() || bundleName.empty() ||
766 sandBoxPath.find(ServiceConstants::SANDBOX_DATA_PATH) == std::string::npos) {
767 APP_LOGE("input sandboxPath or bundleName invalid");
768 return false;
769 }
770
771 realPath = sandBoxPath;
772 std::string relaDataPath = std::string(ServiceConstants::REAL_DATA_PATH) + ServiceConstants::PATH_SEPARATOR
773 + std::to_string(BundleUtil::GetUserIdByCallingUid()) + ServiceConstants::BASE + bundleName;
774 realPath.replace(realPath.find(ServiceConstants::SANDBOX_DATA_PATH),
775 std::string(ServiceConstants::SANDBOX_DATA_PATH).size(), relaDataPath);
776 return true;
777 }
778
StartWith(const std::string &source, const std::string &prefix)779 bool BundleUtil::StartWith(const std::string &source, const std::string &prefix)
780 {
781 if (source.empty() || prefix.empty()) {
782 return false;
783 }
784
785 return source.find(prefix) == 0;
786 }
787
EndWith(const std::string &source, const std::string &suffix)788 bool BundleUtil::EndWith(const std::string &source, const std::string &suffix)
789 {
790 if (source.empty() || suffix.empty()) {
791 return false;
792 }
793
794 auto position = source.rfind(suffix);
795 if (position == std::string::npos) {
796 return false;
797 }
798
799 std::string suffixStr = source.substr(position);
800 return suffixStr == suffix;
801 }
802
GetFileSize(const std::string &filePath)803 int64_t BundleUtil::GetFileSize(const std::string &filePath)
804 {
805 struct stat fileInfo = { 0 };
806 if (stat(filePath.c_str(), &fileInfo) != 0) {
807 APP_LOGE("call stat error:%{public}d", errno);
808 return 0;
809 }
810 return fileInfo.st_size;
811 }
812
CopyFileToSecurityDir(const std::string &filePath, const DirType &dirType, std::vector<std::string> &toDeletePaths)813 std::string BundleUtil::CopyFileToSecurityDir(const std::string &filePath, const DirType &dirType,
814 std::vector<std::string> &toDeletePaths)
815 {
816 APP_LOGD("the original dir is %{public}s", filePath.c_str());
817 std::string destination = "";
818 std::string subStr = "";
819 destination.append(ServiceConstants::HAP_COPY_PATH).append(ServiceConstants::PATH_SEPARATOR);
820 if (dirType == DirType::STREAM_INSTALL_DIR) {
821 subStr = ServiceConstants::STREAM_INSTALL_PATH;
822 destination.append(ServiceConstants::SECURITY_STREAM_INSTALL_PATH);
823 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
824 if (InstalldClient::GetInstance()->Mkdir(
825 destination, mode, Constants::FOUNDATION_UID, ServiceConstants::BMS_GID) != ERR_OK) {
826 APP_LOGW("installd mkdir %{private}s failed", destination.c_str());
827 }
828 }
829 if (dirType == DirType::SIG_FILE_DIR) {
830 subStr = ServiceConstants::SIGNATURE_FILE_PATH;
831 destination.append(ServiceConstants::SECURITY_SIGNATURE_FILE_PATH);
832 }
833 destination.append(ServiceConstants::PATH_SEPARATOR).append(std::to_string(GetCurrentTimeNs()));
834 destination = CreateTempDir(destination);
835 auto pos = filePath.find(subStr);
836 if (pos == std::string::npos) { // this circumstance could not be considered laterly
837 auto lastPathSeperator = filePath.rfind(ServiceConstants::PATH_SEPARATOR);
838 if ((lastPathSeperator != std::string::npos) && (lastPathSeperator != filePath.length() - 1)) {
839 toDeletePaths.emplace_back(destination);
840 destination.append(filePath.substr(lastPathSeperator));
841 }
842 } else {
843 auto secondLastPathSep = filePath.find(ServiceConstants::PATH_SEPARATOR, pos);
844 if ((secondLastPathSep == std::string::npos) || (secondLastPathSep == filePath.length() - 1)) {
845 return "";
846 }
847 auto thirdLastPathSep =
848 filePath.find(ServiceConstants::PATH_SEPARATOR, secondLastPathSep + 1);
849 if ((thirdLastPathSep == std::string::npos) || (thirdLastPathSep == filePath.length() - 1)) {
850 return "";
851 }
852 toDeletePaths.emplace_back(destination);
853 std::string innerSubstr =
854 filePath.substr(secondLastPathSep, thirdLastPathSep - secondLastPathSep + 1);
855 destination = CreateTempDir(destination.append(innerSubstr));
856 destination.append(filePath.substr(thirdLastPathSep + 1));
857 }
858 APP_LOGD("the destination dir is %{public}s", destination.c_str());
859 if (destination.empty()) {
860 return "";
861 }
862 if (!CopyFileFast(filePath, destination)) {
863 APP_LOGE("copy file from %{public}s to %{public}s failed", filePath.c_str(), destination.c_str());
864 return "";
865 }
866 return destination;
867 }
868
DeleteTempDirs(const std::vector<std::string> &tempDirs)869 void BundleUtil::DeleteTempDirs(const std::vector<std::string> &tempDirs)
870 {
871 for (const auto &tempDir : tempDirs) {
872 APP_LOGD("the temp hap dir %{public}s needs to be deleted", tempDir.c_str());
873 BundleUtil::DeleteDir(tempDir);
874 }
875 }
876
GetHexHash(const std::string &s)877 std::string BundleUtil::GetHexHash(const std::string &s)
878 {
879 std::hash<std::string> hasher;
880 size_t hash = hasher(s);
881
882 std::stringstream ss;
883 ss << std::hex << hash;
884
885 std::string hash_str = ss.str();
886 return hash_str;
887 }
888
RecursiveHash(std::string& s)889 void BundleUtil::RecursiveHash(std::string& s)
890 {
891 if (s.size() >= ORIGIN_STRING_LENGTH) {
892 s = s.substr(s.size() - ORIGIN_STRING_LENGTH);
893 return;
894 }
895 std::string hash = GetHexHash(s);
896 s += hash;
897 RecursiveHash(s);
898 }
899
GenerateUuid()900 std::string BundleUtil::GenerateUuid()
901 {
902 std::lock_guard<std::mutex> lock(g_mutex);
903 auto currentTime = std::chrono::system_clock::now();
904 auto timestampNanoseconds =
905 std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime.time_since_epoch()).count();
906
907 // convert nanosecond timestamps to string
908 std::string s = std::to_string(timestampNanoseconds);
909 std::string timeStr = GetHexHash(s);
910
911 char deviceId[UUID_LENGTH_MAX] = { 0 };
912 auto ret = GetDevUdid(deviceId, UUID_LENGTH_MAX);
913 std::string deviceUdid;
914 std::string deviceStr;
915 if (ret != 0) {
916 APP_LOGW("GetDevUdid failed");
917 } else {
918 deviceUdid = std::string{ deviceId };
919 deviceStr = GetHexHash(deviceUdid);
920 }
921
922 std::string uuid = timeStr + deviceStr;
923 RecursiveHash(uuid);
924
925 for (int32_t index : SEPARATOR_POSITIONS) {
926 uuid.insert(index, 1, UUID_SEPARATOR);
927 }
928 return uuid;
929 }
930
GenerateUuidByKey(const std::string &key)931 std::string BundleUtil::GenerateUuidByKey(const std::string &key)
932 {
933 std::string keyHash = GetHexHash(key);
934
935 char deviceId[UUID_LENGTH_MAX] = { 0 };
936 auto ret = GetDevUdid(deviceId, UUID_LENGTH_MAX);
937 std::string deviceUdid;
938 std::string deviceStr;
939 if (ret != 0) {
940 APP_LOGW("GetDevUdid failed");
941 } else {
942 deviceUdid = std::string{ deviceId };
943 deviceStr = GetHexHash(deviceUdid);
944 }
945
946 std::string uuid = keyHash + deviceStr;
947 RecursiveHash(uuid);
948
949 for (int32_t index : SEPARATOR_POSITIONS) {
950 uuid.insert(index, 1, UUID_SEPARATOR);
951 }
952 return uuid;
953 }
954
ExtractGroupIdByDevelopId(const std::string &developerId)955 std::string BundleUtil::ExtractGroupIdByDevelopId(const std::string &developerId)
956 {
957 std::string::size_type dot_position = developerId.find('.');
958 if (dot_position == std::string::npos) {
959 // If cannot find '.' , the input string is developerId, return developerId
960 return developerId;
961 }
962 if (dot_position == 0) {
963 // if'.' In the first place, then groupId is empty, return developerId
964 return developerId.substr(1);
965 }
966 // If '.' If it is not the first place, there is a groupId, and the groupId is returned
967 return developerId.substr(0, dot_position);
968 }
969
ToString(const std::vector<std::string> &vector)970 std::string BundleUtil::ToString(const std::vector<std::string> &vector)
971 {
972 std::string ret;
973 for (const std::string &item : vector) {
974 ret.append(item).append(",");
975 }
976 return ret;
977 }
978
GetNoDisablingConfigPath()979 std::string BundleUtil::GetNoDisablingConfigPath()
980 {
981 #ifdef CONFIG_POLOCY_ENABLE
982 char buf[MAX_PATH_LEN] = { 0 };
983 char *configPath = GetOneCfgFile(NO_DISABLING_CONFIG_PATH, buf, MAX_PATH_LEN);
984 if (configPath == nullptr || configPath[0] == '\0' || strlen(configPath) > MAX_PATH_LEN) {
985 return NO_DISABLING_CONFIG_PATH_DEFAULT;
986 }
987 return configPath;
988 #else
989 return NO_DISABLING_CONFIG_PATH_DEFAULT;
990 #endif
991 }
992 } // namespace AppExecFwk
993 } // namespace OHOS
994