• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "installd/installd_host_impl.h"
17 
18 #include <cinttypes>
19 #include <cstdio>
20 #include <fstream>
21 #include <map>
22 #include <memory>
23 #include <sstream>
24 #include <string>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/xattr.h>
28 #include <unistd.h>
29 
30 #include "aot/aot_executor.h"
31 #include "app_log_tag_wrapper.h"
32 #include "bundle_constants.h"
33 #include "bundle_service_constants.h"
34 #if defined(CODE_SIGNATURE_ENABLE)
35 #include "byte_buffer.h"
36 #include "code_sign_utils.h"
37 #endif
38 #include "common_profile.h"
39 #ifdef CONFIG_POLOCY_ENABLE
40 #include "config_policy_utils.h"
41 #endif
42 #include "directory_ex.h"
43 #ifdef WITH_SELINUX
44 #include "hap_restorecon.h"
45 #include "selinux/selinux.h"
46 #ifndef SELINUX_HAP_DEBUGGABLE
47 #define SELINUX_HAP_DEBUGGABLE 2
48 #endif
49 #endif // WITH_SELINUX
50 #include "installd/installd_operator.h"
51 #include "installd/installd_permission_mgr.h"
52 #include "parameters.h"
53 #include "inner_bundle_clone_common.h"
54 #include "storage_acl.h"
55 
56 namespace OHOS {
57 namespace AppExecFwk {
58 namespace {
59 const std::string ARK_CACHE_PATH = "/data/local/ark-cache/";
60 const std::string ARK_PROFILE_PATH = "/data/local/ark-profile/";
61 const std::vector<std::string> BUNDLE_DATA_DIR = {
62     "/cache",
63     "/files",
64     "/temp",
65     "/preferences",
66     "/haps"
67 };
68 const std::string CLOUD_FILE_PATH = "/data/service/el2/%/hmdfs/cloud/data/";
69 const std::string BUNDLE_BACKUP_HOME_PATH_EL2 = "/data/service/el2/%/backup/bundles/";
70 const std::string DISTRIBUTED_FILE = "/data/service/el2/%/hmdfs/account/data/";
71 const std::string SHARE_FILE_PATH = "/data/service/el2/%/share/";
72 const std::string BUNDLE_BACKUP_HOME_PATH_EL1 = "/data/service/el1/%/backup/bundles/";
73 const std::string DISTRIBUTED_FILE_NON_ACCOUNT = "/data/service/el2/%/hmdfs/non_account/data/";
74 const std::string BUNDLE_BACKUP_HOME_PATH_EL2_NEW = "/data/app/el2/%/base/";
75 const std::string BUNDLE_BACKUP_HOME_PATH_EL1_NEW = "/data/app/el1/%/base/";
76 const std::string BUNDLE_BACKUP_INNER_DIR = "/.backup";
77 constexpr const char* EXTENSION_CONFIG_DEFAULT_PATH = "/system/etc/ams_extension_config.json";
78 #ifdef CONFIG_POLOCY_ENABLE
79 constexpr const char* EXTENSION_CONFIG_FILE_PATH = "/etc/ams_extension_config.json";
80 #endif
81 constexpr const char* EXTENSION_CONFIG_NAME = "ams_extension_config";
82 constexpr const char* EXTENSION_TYPE_NAME = "extension_type_name";
83 constexpr const char* EXTENSION_SERVICE_NEED_CREATE_SANDBOX = "need_create_sandbox";
84 constexpr const char* SHELL_ENTRY_TXT = "g:2000:rwx";
85 constexpr int32_t INSTALLS_UID = 3060;
86 enum class DirType {
87     DIR_EL1,
88     DIR_EL2,
89 };
90 #if defined(CODE_SIGNATURE_ENABLE)
91 using namespace OHOS::Security::CodeSign;
92 #endif
93 }
94 
InstalldHostImpl()95 InstalldHostImpl::InstalldHostImpl()
96 {
97     LOG_I(BMS_TAG_INSTALLD, "installd service instance is created");
98 }
99 
~InstalldHostImpl()100 InstalldHostImpl::~InstalldHostImpl()
101 {
102     LOG_I(BMS_TAG_INSTALLD, "installd service instance is destroyed");
103 }
104 
CreateBundleDir(const std::string & bundleDir)105 ErrCode InstalldHostImpl::CreateBundleDir(const std::string &bundleDir)
106 {
107     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
108         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
109         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
110     }
111     if (bundleDir.empty()) {
112         LOG_E(BMS_TAG_INSTALLD, "Calling the function CreateBundleDir with invalid param");
113         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
114     }
115     if (InstalldOperator::IsExistDir(bundleDir)) {
116         LOG_W(BMS_TAG_INSTALLD, "bundleDir %{public}s is exist", bundleDir.c_str());
117         OHOS::ForceRemoveDirectory(bundleDir);
118     }
119     if (!InstalldOperator::MkRecursiveDir(bundleDir, true)) {
120         LOG_E(BMS_TAG_INSTALLD, "create bundle dir %{public}s failed, errno:%{public}d", bundleDir.c_str(), errno);
121         return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
122     }
123     return ERR_OK;
124 }
125 
ExtractModuleFiles(const std::string & srcModulePath,const std::string & targetPath,const std::string & targetSoPath,const std::string & cpuAbi)126 ErrCode InstalldHostImpl::ExtractModuleFiles(const std::string &srcModulePath, const std::string &targetPath,
127     const std::string &targetSoPath, const std::string &cpuAbi)
128 {
129     LOG_D(BMS_TAG_INSTALLD, "ExtractModuleFiles extract original src %{public}s and target src %{public}s",
130         srcModulePath.c_str(), targetPath.c_str());
131     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
132         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
133         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
134     }
135     if (srcModulePath.empty() || targetPath.empty()) {
136         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractModuleFiles with invalid param");
137         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
138     }
139     if (!InstalldOperator::MkRecursiveDir(targetPath, true)) {
140         LOG_E(BMS_TAG_INSTALLD, "create target dir %{public}s failed, errno:%{public}d", targetPath.c_str(), errno);
141         return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
142     }
143     if (!InstalldOperator::ExtractFiles(srcModulePath, targetSoPath, cpuAbi)) {
144         LOG_E(BMS_TAG_INSTALLD, "extract %{public}s to %{public}s failed errno:%{public}d",
145             srcModulePath.c_str(), targetPath.c_str(), errno);
146         InstalldOperator::DeleteDir(targetPath);
147         return ERR_APPEXECFWK_INSTALL_DISK_MEM_INSUFFICIENT;
148     }
149     return ERR_OK;
150 }
151 
ExtractFiles(const ExtractParam & extractParam)152 ErrCode InstalldHostImpl::ExtractFiles(const ExtractParam &extractParam)
153 {
154     LOG_D(BMS_TAG_INSTALLD, "ExtractFiles extractParam %{public}s", extractParam.ToString().c_str());
155     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
156         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
157         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
158     }
159 
160     if (extractParam.srcPath.empty() || extractParam.targetPath.empty()) {
161         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractFiles with invalid param");
162         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
163     }
164 
165     if (!InstalldOperator::ExtractFiles(extractParam)) {
166         LOG_E(BMS_TAG_INSTALLD, "extract failed errno:%{public}d", errno);
167         return ERR_APPEXECFWK_INSTALL_DISK_MEM_INSUFFICIENT;
168     }
169 
170     return ERR_OK;
171 }
172 
173 
ExtractHnpFiles(const std::string & hnpPackageInfo,const ExtractParam & extractParam)174 ErrCode InstalldHostImpl::ExtractHnpFiles(const std::string &hnpPackageInfo, const ExtractParam &extractParam)
175 {
176     LOG_D(BMS_TAG_INSTALLD, "ExtractHnpFiles hnpPackageInfo %{public}s", hnpPackageInfo.c_str());
177     LOG_D(BMS_TAG_INSTALLD, "ExtractHnpFiles extractParam %{public}s", extractParam.ToString().c_str());
178     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
179         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
180         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
181     }
182 
183     if (extractParam.srcPath.empty() || extractParam.targetPath.empty() || hnpPackageInfo.empty()) {
184         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractFiles with invalid param");
185         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
186     }
187 
188     if (!InstalldOperator::ExtractFiles(hnpPackageInfo, extractParam)) {
189         LOG_E(BMS_TAG_INSTALLD, "extract failed errno:%{public}d", errno);
190         return ERR_APPEXECFWK_NATIVE_HNP_EXTRACT_FAILED;
191     }
192 
193     return ERR_OK;
194 }
195 
ProcessBundleInstallNative(const std::string & userId,const std::string & hnpRootPath,const std::string & hapPath,const std::string & cpuAbi,const std::string & packageName)196 ErrCode InstalldHostImpl::ProcessBundleInstallNative(const std::string &userId, const std::string &hnpRootPath,
197     const std::string &hapPath, const std::string &cpuAbi, const std::string &packageName)
198 {
199     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
200         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
201         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
202     }
203     if (!InstalldOperator::ProcessBundleInstallNative(userId, hnpRootPath, hapPath, cpuAbi, packageName)) {
204         return ERR_APPEXECFWK_NATIVE_INSTALL_FAILED;
205     }
206     return ERR_OK;
207 }
208 
ProcessBundleUnInstallNative(const std::string & userId,const std::string & packageName)209 ErrCode InstalldHostImpl::ProcessBundleUnInstallNative(const std::string &userId, const std::string &packageName)
210 {
211     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
212         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
213         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
214     }
215     if (!InstalldOperator::ProcessBundleUnInstallNative(userId, packageName)) {
216         return ERR_APPEXECFWK_NATIVE_UNINSTALL_FAILED;
217     }
218     return ERR_OK;
219 }
220 
ExecuteAOT(const AOTArgs & aotArgs,std::vector<uint8_t> & pendSignData)221 ErrCode InstalldHostImpl::ExecuteAOT(const AOTArgs &aotArgs, std::vector<uint8_t> &pendSignData)
222 {
223     LOG_D(BMS_TAG_INSTALLD, "begin to execute AOT, args : %{public}s", aotArgs.ToString().c_str());
224     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
225         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
226         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
227     }
228     ErrCode ret = ERR_OK;
229     AOTExecutor::GetInstance().ExecuteAOT(aotArgs, ret, pendSignData);
230     LOG_D(BMS_TAG_INSTALLD, "execute AOT ret : %{public}d", ret);
231     return ret;
232 }
233 
PendSignAOT(const std::string & anFileName,const std::vector<uint8_t> & signData)234 ErrCode InstalldHostImpl::PendSignAOT(const std::string &anFileName, const std::vector<uint8_t> &signData)
235 {
236     LOG_D(BMS_TAG_INSTALLD, "begin to pend sign AOT, anFileName : %{public}s", anFileName.c_str());
237     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
238         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
239         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
240     }
241     ErrCode ret = AOTExecutor::GetInstance().PendSignAOT(anFileName, signData);
242     LOG_D(BMS_TAG_INSTALLD, "pend sign AOT ret : %{public}d", ret);
243     return ret;
244 }
245 
StopAOT()246 ErrCode InstalldHostImpl::StopAOT()
247 {
248     LOG_I(BMS_TAG_INSTALLD, "StopAOT begin");
249     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
250         LOG_E(BMS_TAG_INSTALLD, "verify permission failed");
251         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
252     }
253     return AOTExecutor::GetInstance().StopAOT();
254 }
255 
DeleteUninstallTmpDirs(const std::vector<std::string> & dirs)256 ErrCode InstalldHostImpl::DeleteUninstallTmpDirs(const std::vector<std::string> &dirs)
257 {
258     LOG_I(BMS_TAG_INSTALLD, "DeleteUninstallTmpDirs begin");
259     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
260         LOG_E(BMS_TAG_INSTALLD, "verify permission failed");
261         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
262     }
263     ErrCode ret = ERR_OK;
264     for (const std::string &dir : dirs) {
265         if (!InstalldOperator::DeleteUninstallTmpDir(dir)) {
266             ret = ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
267         }
268     }
269     return ret;
270 }
271 
RenameModuleDir(const std::string & oldPath,const std::string & newPath)272 ErrCode InstalldHostImpl::RenameModuleDir(const std::string &oldPath, const std::string &newPath)
273 {
274     LOG_D(BMS_TAG_INSTALLD, "rename %{public}s to %{public}s", oldPath.c_str(), newPath.c_str());
275     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
276         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
277         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
278     }
279     if (oldPath.empty() || newPath.empty()) {
280         LOG_E(BMS_TAG_INSTALLD, "Calling the function RenameModuleDir with invalid param");
281         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
282     }
283     if (!InstalldOperator::RenameDir(oldPath, newPath)) {
284         LOG_D(BMS_TAG_INSTALLD, "rename module dir %{public}s to %{public}s failed errno:%{public}d",
285             oldPath.c_str(), newPath.c_str(), errno);
286         return ERR_APPEXECFWK_INSTALLD_RNAME_DIR_FAILED;
287     }
288     return ERR_OK;
289 }
290 
GetBackupExtDirByType(std::string & bundleBackupDir,const std::string & bundleName,const DirType dirType)291 static void GetBackupExtDirByType(std::string &bundleBackupDir, const std::string &bundleName, const DirType dirType)
292 {
293     switch (dirType) {
294         case DirType::DIR_EL1:
295             bundleBackupDir = BUNDLE_BACKUP_HOME_PATH_EL1 + bundleName;
296             break;
297         case DirType::DIR_EL2:
298             bundleBackupDir = BUNDLE_BACKUP_HOME_PATH_EL2 + bundleName;
299             break;
300         default:
301             break;
302     }
303 }
304 
GetNewBackupExtDirByType(std::string & bundleBackupDir,const std::string & bundleName,const DirType dirType)305 static void GetNewBackupExtDirByType(std::string &bundleBackupDir,
306     const std::string &bundleName, const DirType dirType)
307 {
308     switch (dirType) {
309         case DirType::DIR_EL1:
310             bundleBackupDir = BUNDLE_BACKUP_HOME_PATH_EL1_NEW + bundleName + BUNDLE_BACKUP_INNER_DIR;
311             break;
312         case DirType::DIR_EL2:
313             bundleBackupDir = BUNDLE_BACKUP_HOME_PATH_EL2_NEW + bundleName + BUNDLE_BACKUP_INNER_DIR;
314             break;
315         default:
316             break;
317     }
318 }
319 
CreateBackupExtHomeDir(const std::string & bundleName,const int32_t userid,const int32_t uid,std::string & bundleBackupDir,const DirType dirType)320 static void CreateBackupExtHomeDir(const std::string &bundleName, const int32_t userid, const int32_t uid,
321     std::string &bundleBackupDir, const DirType dirType)
322 {
323     GetBackupExtDirByType(bundleBackupDir, bundleName, dirType);
324     LOG_D(BMS_TAG_INSTALLD, "CreateBackupExtHomeDir begin, type %{public}d, path %{public}s",
325         dirType, bundleBackupDir.c_str());
326     if (bundleBackupDir.empty()) {
327         LOG_W(BMS_TAG_INSTALLD, "CreateBackupExtHomeDir backup dir empty, type  %{public}d", dirType);
328         return;
329     }
330     // Setup BackupExtensionAbility's home directory in a harmless way
331     bundleBackupDir = bundleBackupDir.replace(bundleBackupDir.find("%"), 1, std::to_string(userid));
332     if (!InstalldOperator::MkOwnerDir(
333         bundleBackupDir, S_IRWXU | S_IRWXG | S_ISGID, uid, ServiceConstants::BACKU_HOME_GID)) {
334         static std::once_flag logOnce;
335         std::call_once(logOnce, []() {
336             LOG_W(BMS_TAG_INSTALLD, "CreateBackupExtHomeDir MkOwnerDir(backup's home dir) failed errno:%{public}d",
337                 errno);
338         });
339     }
340 }
341 
CreateNewBackupExtHomeDir(const std::string & bundleName,const int32_t userid,const int32_t uid,std::string & bundleBackupDir,const DirType dirType)342 static void CreateNewBackupExtHomeDir(const std::string &bundleName, const int32_t userid, const int32_t uid,
343     std::string &bundleBackupDir, const DirType dirType)
344 {
345     GetNewBackupExtDirByType(bundleBackupDir, bundleName, dirType);
346     LOG_D(BMS_TAG_INSTALLD, "CreateNewBackupExtHomeDir begin, type %{public}d, path %{public}s",
347         dirType, bundleBackupDir.c_str());
348     if (bundleBackupDir.empty()) {
349         LOG_W(BMS_TAG_INSTALLD, "CreateNewBackupExtHomeDir backup dir empty, type  %{public}d", dirType);
350         return;
351     }
352     // Setup BackupExtensionAbility's home directory in a harmless way
353     bundleBackupDir = bundleBackupDir.replace(bundleBackupDir.find("%"), 1, std::to_string(userid));
354     if (!InstalldOperator::MkOwnerDir(
355         bundleBackupDir, S_IRWXU | S_IRWXG | S_ISGID, uid, ServiceConstants::BACKU_HOME_GID)) {
356         static std::once_flag logOnce;
357         std::call_once(logOnce, []() {
358             LOG_W(BMS_TAG_INSTALLD, "CreateNewBackupExtHomeDir MkOwnerDir(backup's home dir) failed errno:%{public}d",
359                 errno);
360         });
361     }
362 }
363 
CreateShareDir(const std::string & bundleName,const int32_t userid,const int32_t uid,const int32_t gid)364 static void CreateShareDir(const std::string &bundleName, const int32_t userid, const int32_t uid, const int32_t gid)
365 {
366     std::string bundleShareDir = SHARE_FILE_PATH + bundleName;
367     bundleShareDir = bundleShareDir.replace(bundleShareDir.find("%"), 1, std::to_string(userid));
368     if (!InstalldOperator::MkOwnerDir(bundleShareDir, S_IRWXU | S_IRWXG | S_ISGID, uid, gid)) {
369         static std::once_flag logOnce;
370         std::call_once(logOnce, []() {
371             LOG_W(BMS_TAG_INSTALLD, "CreateShareDir MkOwnerDir(share's home dir) failed errno:%{public}d", errno);
372         });
373     }
374 }
375 
CreateCloudDir(const std::string & bundleName,const int32_t userid,const int32_t uid,const int32_t gid)376 static void CreateCloudDir(const std::string &bundleName, const int32_t userid, const int32_t uid, const int32_t gid)
377 {
378     std::string bundleCloudDir = CLOUD_FILE_PATH + bundleName;
379     bundleCloudDir = bundleCloudDir.replace(bundleCloudDir.find("%"), 1, std::to_string(userid));
380     if (!InstalldOperator::MkOwnerDir(bundleCloudDir, S_IRWXU | S_IRWXG | S_ISGID, uid, gid)) {
381         static std::once_flag logOnce;
382         std::call_once(logOnce, []() {
383             LOG_W(BMS_TAG_INSTALLD, "CreateCloudDir MkOwnerDir(cloud's home dir) failed errno:%{public}d", errno);
384         });
385     }
386 }
CreateBundleDataDirWithVector(const std::vector<CreateDirParam> & createDirParams)387 ErrCode InstalldHostImpl::CreateBundleDataDirWithVector(const std::vector<CreateDirParam> &createDirParams)
388 {
389     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
390         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
391         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
392     }
393     ErrCode res = ERR_OK;
394     for (const auto &item : createDirParams) {
395         ErrCode result = ERR_OK;
396         if (item.dataDirEl == DataDirEl::NONE) {
397             result = CreateBundleDataDir(item);
398         } else {
399             result = CreateBundleDataDirWithEl(item);
400         }
401         if (result != ERR_OK) {
402             LOG_E(BMS_TAG_INSTALLD, "CreateBundleDataDir failed in %{public}s, errCode is %{public}d",
403                 item.bundleName.c_str(), result);
404             res = result;
405         }
406     }
407     return res;
408 }
409 
AclSetDir(bool debug,const std::string & dir,bool setAccess,bool setDefault)410 ErrCode InstalldHostImpl::AclSetDir(bool debug, const std::string &dir, bool setAccess, bool setDefault)
411 {
412     if (!debug) {
413         return ERR_OK;
414     }
415     if (setAccess) {
416         int status = StorageDaemon::AclSetAccess(dir, SHELL_ENTRY_TXT);
417         LOG_I(BMS_TAG_INSTALLD, "AclSetAccess: %{public}d, %{private}s", status, dir.c_str());
418     }
419     if (setDefault) {
420         int status = StorageDaemon::AclSetDefault(dir, SHELL_ENTRY_TXT);
421         LOG_I(BMS_TAG_INSTALLD, "AclSetDefault: %{public}d, %{private}s", status, dir.c_str());
422     }
423     return ERR_OK;
424 }
425 
AclSetExtensionDirs(bool debug,const std::string & parentDir,const std::vector<std::string> & extensionDirs,bool setAccess,bool setDefault)426 ErrCode InstalldHostImpl::AclSetExtensionDirs(bool debug, const std::string &parentDir,
427     const std::vector<std::string> &extensionDirs, bool setAccess, bool setDefault)
428 {
429     if (!debug) {
430         return ERR_OK;
431     }
432     if (extensionDirs.empty()) {
433         return ERR_OK;
434     }
435     for (const auto &extension : extensionDirs) {
436         std::string extensionDir = parentDir + extension;
437         AclSetDir(debug, extensionDir, setAccess, setDefault);
438     }
439     return ERR_OK;
440 }
441 
CreateBundleDataDir(const CreateDirParam & createDirParam)442 ErrCode InstalldHostImpl::CreateBundleDataDir(const CreateDirParam &createDirParam)
443 {
444     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
445         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
446         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
447     }
448     if (createDirParam.bundleName.empty() || createDirParam.userId < 0 ||
449         createDirParam.uid < 0 || createDirParam.gid < 0) {
450         LOG_E(BMS_TAG_INSTALLD, "Calling the function CreateBundleDataDir with invalid param, bundleName %{public}s "
451             "userId %{public}d uid %{public}d gid %{public}d", createDirParam.bundleName.c_str(),
452             createDirParam.userId, createDirParam.uid, createDirParam.gid);
453         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
454     }
455     unsigned int hapFlags = GetHapFlags(createDirParam.isPreInstallApp, createDirParam.debug,
456         createDirParam.isDlpSandbox);
457     for (const auto &el : ServiceConstants::BUNDLE_EL) {
458         if ((createDirParam.createDirFlag == CreateDirFlag::CREATE_DIR_UNLOCKED) &&
459             (el == ServiceConstants::BUNDLE_EL[0])) {
460             continue;
461         }
462 
463         std::string bundleDataDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::BASE;
464         if (access(bundleDataDir.c_str(), F_OK) != 0) {
465             LOG_W(BMS_TAG_INSTALLD, "Base directory %{public}s does not existed, bundleName:%{public}s",
466                 bundleDataDir.c_str(), createDirParam.bundleName.c_str());
467             return ERR_OK;
468         }
469         // create base extension dir
470         int mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_IRWXO) : S_IRWXU;
471         if (CreateExtensionDir(createDirParam, bundleDataDir, mode, createDirParam.gid) != ERR_OK) {
472             LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", bundleDataDir.c_str());
473         }
474         AclSetExtensionDirs(createDirParam.debug, bundleDataDir, createDirParam.extensionDirs, true, true);
475         bundleDataDir += createDirParam.bundleName;
476         if (!InstalldOperator::MkOwnerDir(bundleDataDir, mode, createDirParam.uid, createDirParam.gid)) {
477             LOG_E(BMS_TAG_INSTALLD, "CreateBundledatadir MkOwnerDir failed errno:%{public}d", errno);
478             return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
479         }
480         AclSetDir(createDirParam.debug, bundleDataDir, true, true);
481         if (el == ServiceConstants::BUNDLE_EL[1]) {
482             for (const auto &dir : BUNDLE_DATA_DIR) {
483                 if (!InstalldOperator::MkOwnerDir(bundleDataDir + dir, mode,
484                     createDirParam.uid, createDirParam.gid)) {
485                     LOG_E(BMS_TAG_INSTALLD, "CreateBundledatadir MkOwnerDir el2 failed errno:%{public}d", errno);
486                     return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
487                 }
488             }
489             std::string logParentDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::LOG;
490             std::string logDir = logParentDir + createDirParam.bundleName;
491             if (!InstalldOperator::MkOwnerDir(
492                 logDir, S_IRWXU | S_IRWXG, createDirParam.uid, ServiceConstants::LOG_DIR_GID)) {
493                 LOG_E(BMS_TAG_INSTALLD, "create log dir failed errno:%{public}d", errno);
494                 return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
495             }
496             // create log extension dir
497             if (CreateExtensionDir(createDirParam, logParentDir, S_IRWXU | S_IRWXG,
498                 ServiceConstants::LOG_DIR_GID, true) != ERR_OK) {
499                 LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", logParentDir.c_str());
500             }
501         }
502         ErrCode ret = SetDirApl(bundleDataDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
503         if (ret != ERR_OK) {
504             LOG_E(BMS_TAG_INSTALLD, "CreateBundleDataDir SetDirApl failed");
505             return ret;
506         }
507         std::string databaseParentDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::DATABASE;
508         std::string databaseDir = databaseParentDir + createDirParam.bundleName;
509         mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_ISGID | S_IROTH | S_IXOTH) : (S_IRWXU | S_IRWXG | S_ISGID);
510         if (!InstalldOperator::MkOwnerDir(
511             databaseDir, mode, createDirParam.uid, ServiceConstants::DATABASE_DIR_GID)) {
512             LOG_E(BMS_TAG_INSTALLD, "CreateBundle databaseDir MkOwnerDir failed errno:%{public}d", errno);
513             return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
514         }
515         AclSetDir(createDirParam.debug, databaseDir, false, true);
516         ret = SetDirApl(databaseDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
517         if (ret != ERR_OK) {
518             LOG_E(BMS_TAG_INSTALLD, "CreateBundleDataDir SetDirApl failed");
519             return ret;
520         }
521         // create database extension dir
522         if (CreateExtensionDir(createDirParam, databaseParentDir, mode,
523             ServiceConstants::DATABASE_DIR_GID) != ERR_OK) {
524             LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", databaseParentDir.c_str());
525         }
526         AclSetExtensionDirs(createDirParam.debug, databaseParentDir, createDirParam.extensionDirs, false, true);
527     }
528     std::string distributedfile = DISTRIBUTED_FILE;
529     distributedfile = distributedfile.replace(distributedfile.find("%"), 1, std::to_string(createDirParam.userId));
530     if (!InstalldOperator::MkOwnerDir(distributedfile + createDirParam.bundleName,
531         S_IRWXU | S_IRWXG | S_ISGID, createDirParam.uid, ServiceConstants::DFS_GID)) {
532         LOG_E(BMS_TAG_INSTALLD, "Failed to mk dir for distributedfile errno:%{public}d", errno);
533     }
534 
535     distributedfile = DISTRIBUTED_FILE_NON_ACCOUNT;
536     distributedfile = distributedfile.replace(distributedfile.find("%"), 1, std::to_string(createDirParam.userId));
537     if (!InstalldOperator::MkOwnerDir(distributedfile + createDirParam.bundleName,
538         S_IRWXU | S_IRWXG | S_ISGID, createDirParam.uid, ServiceConstants::DFS_GID)) {
539         LOG_E(BMS_TAG_INSTALLD, "Failed to mk dir for non account distributedfile errno:%{public}d", errno);
540     }
541 
542     std::string bundleBackupDir;
543     CreateBackupExtHomeDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, bundleBackupDir,
544         DirType::DIR_EL2);
545     ErrCode ret = SetDirApl(bundleBackupDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
546     if (ret != ERR_OK) {
547         LOG_E(BMS_TAG_INSTALLD, "CreateBackupExtHomeDir DIR_EL2 SetDirApl failed, errno is %{public}d", ret);
548     }
549 
550     CreateBackupExtHomeDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, bundleBackupDir,
551         DirType::DIR_EL1);
552     ret = SetDirApl(bundleBackupDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
553     if (ret != ERR_OK) {
554         LOG_E(BMS_TAG_INSTALLD, "CreateBackupExtHomeDir DIR_EL1 SetDirApl failed, errno is %{public}d", ret);
555     }
556 
557     std::string newBundleBackupDir;
558     CreateNewBackupExtHomeDir(createDirParam.bundleName,
559         createDirParam.userId, createDirParam.uid, newBundleBackupDir, DirType::DIR_EL2);
560     ret = SetDirApl(newBundleBackupDir, createDirParam.bundleName, createDirParam.apl,
561         createDirParam.isPreInstallApp, createDirParam.debug);
562     if (ret != ERR_OK) {
563         LOG_E(BMS_TAG_INSTALLD, "CreateNewBackupExtHomeDir DIR_EL2 SetDirApl failed, errno is %{public}d", ret);
564     }
565     CreateNewBackupExtHomeDir(createDirParam.bundleName,
566         createDirParam.userId, createDirParam.uid, newBundleBackupDir, DirType::DIR_EL1);
567     ret = SetDirApl(newBundleBackupDir, createDirParam.bundleName, createDirParam.apl,
568         createDirParam.isPreInstallApp, createDirParam.debug);
569     if (ret != ERR_OK) {
570         LOG_E(BMS_TAG_INSTALLD, "CreateNewBackupExtHomeDir DIR_EL1 SetDirApl failed, errno is %{public}d", ret);
571     }
572 
573     CreateShareDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, createDirParam.gid);
574     CreateCloudDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, ServiceConstants::DFS_GID);
575     return ERR_OK;
576 }
577 
CreateBundleDataDirWithEl(const CreateDirParam & createDirParam)578 ErrCode InstalldHostImpl::CreateBundleDataDirWithEl(const CreateDirParam &createDirParam)
579 {
580     LOG_I(BMS_TAG_INSTALLD, "%{public}s begin, %{public}d, el %{public}" PRIu8 "",
581         createDirParam.bundleName.c_str(), createDirParam.userId, static_cast<uint8_t>(createDirParam.dataDirEl));
582     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
583         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
584         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
585     }
586     if (createDirParam.bundleName.empty() || createDirParam.userId < 0 ||
587         createDirParam.uid < 0 || createDirParam.gid < 0) {
588         LOG_E(BMS_TAG_INSTALLD, "invalid param, bundleName %{public}s userId %{public}d uid %{public}d gid %{public}d",
589             createDirParam.bundleName.c_str(), createDirParam.userId, createDirParam.uid, createDirParam.gid);
590         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
591     }
592     if (createDirParam.dataDirEl == DataDirEl::NONE || createDirParam.dataDirEl == DataDirEl::EL1 ||
593         createDirParam.dataDirEl == DataDirEl::EL5) {
594         LOG_E(BMS_TAG_INSTALLD, "invalid el: %{public}d", static_cast<uint8_t>(createDirParam.dataDirEl));
595         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
596     }
597     uint32_t index = static_cast<uint32_t>(createDirParam.dataDirEl) - 1;
598     if (index >= ServiceConstants::BUNDLE_EL.size()) {
599         LOG_E(BMS_TAG_INSTALLD, "invalid dataDirEl %{public}d", index);
600         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
601     }
602     std::string el = ServiceConstants::BUNDLE_EL[index];
603     std::string bundleDataDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::BASE;
604     if (access(bundleDataDir.c_str(), F_OK) != 0) {
605         LOG_W(BMS_TAG_INSTALLD, "Base directory %{public}s does not existed, bundleName:%{public}s",
606             bundleDataDir.c_str(), createDirParam.bundleName.c_str());
607         return ERR_OK;
608     }
609     ErrCode ret = ERR_OK;
610     // create common dirs for all el: ${bundleName} and ${extension} under base and database
611     ret = CreateCommonDataDir(createDirParam, el);
612     if (ret != ERR_OK) {
613         LOG_E(BMS_TAG_INSTALLD, "CreateCommonDataDir failed %{public}d", ret);
614         return ret;
615     }
616     // create dirs unique to el2
617     if (createDirParam.dataDirEl == DataDirEl::EL2) {
618         ret = CreateEl2DataDir(createDirParam);
619         if (ret != ERR_OK) {
620             LOG_E(BMS_TAG_INSTALLD, "CreateEl2DataDir failed %{public}d", ret);
621             return ret;
622         }
623     }
624     return ret;
625 }
626 
CreateCommonDataDir(const CreateDirParam & createDirParam,const std::string & el)627 ErrCode InstalldHostImpl::CreateCommonDataDir(const CreateDirParam &createDirParam, const std::string &el)
628 {
629     if (createDirParam.dataDirEl == DataDirEl::NONE || createDirParam.dataDirEl == DataDirEl::EL5) {
630         LOG_I(BMS_TAG_INSTALLD, "el not support: %{public}" PRIu8 "", static_cast<uint8_t>(createDirParam.dataDirEl));
631         return ERR_OK;
632     }
633     unsigned int hapFlags = GetHapFlags(createDirParam.isPreInstallApp, createDirParam.debug,
634         createDirParam.isDlpSandbox);
635     std::string bundleDataDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::BASE;
636     int mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_IRWXO) : S_IRWXU;
637 
638     // create base extension dir: /data/app/${elx}/${userId}/base/${extensionDir}
639     if (CreateExtensionDir(createDirParam, bundleDataDir, mode, createDirParam.gid) != ERR_OK) {
640         LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", bundleDataDir.c_str());
641     }
642     AclSetExtensionDirs(createDirParam.debug, bundleDataDir, createDirParam.extensionDirs, true, true);
643 
644     // create base bundleName dir: /data/app/${elx}/${userId}/base/${bundleName}
645     bundleDataDir += createDirParam.bundleName;
646     if (!InstalldOperator::MkOwnerDir(bundleDataDir, mode, createDirParam.uid, createDirParam.gid)) {
647         LOG_E(BMS_TAG_INSTALLD, "CreateBundledatadir MkOwnerDir failed errno:%{public}d", errno);
648         return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
649     }
650     AclSetDir(createDirParam.debug, bundleDataDir, true, true);
651     ErrCode ret = SetDirApl(bundleDataDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
652     if (ret != ERR_OK) {
653         LOG_E(BMS_TAG_INSTALLD, "CreateBundleDataDir SetDirApl failed");
654         return ret;
655     }
656 
657     // create database bundleName dir: /data/app/${elx}/${userId}/database/${bundleName}
658     std::string databaseParentDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::DATABASE;
659     std::string databaseDir = databaseParentDir + createDirParam.bundleName;
660     mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_ISGID | S_IROTH | S_IXOTH) : (S_IRWXU | S_IRWXG | S_ISGID);
661     if (!InstalldOperator::MkOwnerDir(
662         databaseDir, mode, createDirParam.uid, ServiceConstants::DATABASE_DIR_GID)) {
663         LOG_E(BMS_TAG_INSTALLD, "CreateBundle databaseDir MkOwnerDir failed errno:%{public}d", errno);
664         return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
665     }
666     AclSetDir(createDirParam.debug, databaseDir, false, true);
667     ret = SetDirApl(databaseDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
668     if (ret != ERR_OK) {
669         LOG_E(BMS_TAG_INSTALLD, "CreateBundleDataDir SetDirApl failed");
670         return ret;
671     }
672 
673     // create database extension dir: /data/app/${elx}/${userId}/database/${extensionDir}
674     if (CreateExtensionDir(createDirParam, databaseParentDir, mode,
675         ServiceConstants::DATABASE_DIR_GID) != ERR_OK) {
676         LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", databaseParentDir.c_str());
677     }
678     AclSetExtensionDirs(createDirParam.debug, databaseParentDir, createDirParam.extensionDirs, false, true);
679     return ERR_OK;
680 }
681 
CreateEl2DataDir(const CreateDirParam & createDirParam)682 ErrCode InstalldHostImpl::CreateEl2DataDir(const CreateDirParam &createDirParam)
683 {
684     std::string el = ServiceConstants::DIR_EL2;
685     std::string bundleDataDir = GetBundleDataDir(el, createDirParam.userId) +
686         ServiceConstants::BASE + createDirParam.bundleName;
687     int mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_IRWXO) : S_IRWXU;
688 
689     // create el2 sub dir: /data/app/el2/${userId}/base/${bundleName}/cache|files|temp|preferences|haps
690     for (const auto &dir : BUNDLE_DATA_DIR) {
691         if (!InstalldOperator::MkOwnerDir(bundleDataDir + dir, mode,
692             createDirParam.uid, createDirParam.gid)) {
693             LOG_E(BMS_TAG_INSTALLD, "CreateBundledatadir MkOwnerDir el2 failed errno:%{public}d", errno);
694             return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
695         }
696     }
697 
698     // create log dir: /data/app/el2/${userId}/log/${bundleName}
699     std::string logParentDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::LOG;
700     std::string logDir = logParentDir + createDirParam.bundleName;
701     if (!InstalldOperator::MkOwnerDir(
702         logDir, S_IRWXU | S_IRWXG, createDirParam.uid, ServiceConstants::LOG_DIR_GID)) {
703         LOG_E(BMS_TAG_INSTALLD, "create log dir failed errno:%{public}d", errno);
704         return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
705     }
706 
707     // create log extension dir: /data/app/el2/${userId}/log/${extensionDir}
708     if (CreateExtensionDir(createDirParam, logParentDir, S_IRWXU | S_IRWXG,
709         ServiceConstants::LOG_DIR_GID, true) != ERR_OK) {
710         LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", logParentDir.c_str());
711     }
712 
713     // /data/service/el2/${userId}/hmdfs/account/data/${bundleName}
714     std::string distributedfile = DISTRIBUTED_FILE;
715     distributedfile = distributedfile.replace(distributedfile.find("%"), 1, std::to_string(createDirParam.userId));
716     if (!InstalldOperator::MkOwnerDir(distributedfile + createDirParam.bundleName,
717         S_IRWXU | S_IRWXG | S_ISGID, createDirParam.uid, ServiceConstants::DFS_GID)) {
718         LOG_E(BMS_TAG_INSTALLD, "Failed to mk dir for distributedfile errno:%{public}d", errno);
719     }
720 
721     // /data/service/el2/${userId}/hmdfs/non_account/data/${bundleName}
722     distributedfile = DISTRIBUTED_FILE_NON_ACCOUNT;
723     distributedfile = distributedfile.replace(distributedfile.find("%"), 1, std::to_string(createDirParam.userId));
724     if (!InstalldOperator::MkOwnerDir(distributedfile + createDirParam.bundleName,
725         S_IRWXU | S_IRWXG | S_ISGID, createDirParam.uid, ServiceConstants::DFS_GID)) {
726         LOG_E(BMS_TAG_INSTALLD, "Failed to mk dir for non account distributedfile errno:%{public}d", errno);
727     }
728 
729     // /data/service/el2/${userId}/backup/bundles/${bundleName}
730     std::string bundleBackupDir;
731     CreateBackupExtHomeDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, bundleBackupDir,
732         DirType::DIR_EL2);
733     unsigned int hapFlags = GetHapFlags(createDirParam.isPreInstallApp, createDirParam.debug,
734         createDirParam.isDlpSandbox);
735     ErrCode ret = SetDirApl(bundleBackupDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
736     if (ret != ERR_OK) {
737         LOG_E(BMS_TAG_INSTALLD, "CreateBackupExtHomeDir DIR_EL2 SetDirApl failed, errno is %{public}d", ret);
738     }
739 
740     // /data/app/el2/${userId}/base/${bundleName}/.backup
741     std::string newBundleBackupDir;
742     CreateNewBackupExtHomeDir(createDirParam.bundleName,
743         createDirParam.userId, createDirParam.uid, newBundleBackupDir, DirType::DIR_EL2);
744     ret = SetDirApl(newBundleBackupDir, createDirParam.bundleName, createDirParam.apl,
745         createDirParam.isPreInstallApp, createDirParam.debug);
746     if (ret != ERR_OK) {
747         LOG_E(BMS_TAG_INSTALLD, "CreateNewBackupExtHomeDir DIR_EL2 SetDirApl failed, errno is %{public}d", ret);
748     }
749 
750     // /data/service/el2/${userId}/share/${bundleName}
751     CreateShareDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, createDirParam.gid);
752 
753     // /data/service/el2/${userId}/hmdfs/cloud/data/${bundleName}
754     CreateCloudDir(createDirParam.bundleName, createDirParam.userId, createDirParam.uid, ServiceConstants::DFS_GID);
755     return ERR_OK;
756 }
757 
CreateExtensionDir(const CreateDirParam & createDirParam,const std::string & parentDir,int32_t mode,int32_t gid,bool isLog)758 ErrCode InstalldHostImpl::CreateExtensionDir(const CreateDirParam &createDirParam, const std::string& parentDir,
759     int32_t mode, int32_t gid, bool isLog)
760 {
761     if (createDirParam.extensionDirs.empty()) {
762         return ERR_OK;
763     }
764     unsigned int hapFlags = GetHapFlags(createDirParam.isPreInstallApp, createDirParam.debug,
765         createDirParam.isDlpSandbox);
766     LOG_I(BMS_TAG_INSTALLD, "CreateExtensionDir parent dir %{public}s for bundle %{public}s",
767         parentDir.c_str(), createDirParam.bundleName.c_str());
768     for (const auto &item : createDirParam.extensionDirs) {
769         std::string extensionDir = parentDir + item;
770         LOG_I(BMS_TAG_INSTALLD, "begin to create extension dir %{public}s", extensionDir.c_str());
771         if (!InstalldOperator::MkOwnerDir(
772             extensionDir, mode, createDirParam.uid, gid)) {
773             LOG_E(BMS_TAG_INSTALLD, "CreateExtension dir %{public}s error %{public}s",
774                 extensionDir.c_str(), strerror(errno));
775             return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
776         }
777         if (isLog) {
778             continue;
779         }
780         auto ret = SetDirApl(extensionDir, createDirParam.bundleName, createDirParam.apl, hapFlags);
781         if (ret != ERR_OK) {
782             LOG_E(BMS_TAG_INSTALLD, "dir %{public}s SetDirApl failed", extensionDir.c_str());
783             return ret;
784         }
785     }
786     return ERR_OK;
787 }
788 
RemoveBackupExtHomeDir(const std::string & bundleName,const int userid,DirType dirType)789 static ErrCode RemoveBackupExtHomeDir(const std::string &bundleName, const int userid, DirType dirType)
790 {
791     std::string bundleBackupDir;
792     GetBackupExtDirByType(bundleBackupDir, bundleName, dirType);
793     LOG_D(BMS_TAG_INSTALLD, "RemoveBackupExtHomeDir begin, type %{public}d, path %{public}s",
794         dirType, bundleBackupDir.c_str());
795     if (bundleBackupDir.empty()) {
796         LOG_W(BMS_TAG_INSTALLD, "RemoveBackupExtHomeDir backup dir empty, type  %{public}d", dirType);
797         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
798     }
799     bundleBackupDir = bundleBackupDir.replace(bundleBackupDir.find("%"), 1, std::to_string(userid));
800     if (!InstalldOperator::DeleteDir(bundleBackupDir)) {
801         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed, errno is %{public}d", bundleBackupDir.c_str(), errno);
802         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
803     }
804     return ERR_OK;
805 }
806 
RemoveNewBackupExtHomeDir(const std::string & bundleName,const int userid,DirType dirType)807 static ErrCode RemoveNewBackupExtHomeDir(const std::string &bundleName, const int userid, DirType dirType)
808 {
809     std::string bundleBackupDir;
810     GetNewBackupExtDirByType(bundleBackupDir, bundleName, dirType);
811     LOG_D(BMS_TAG_INSTALLD, "RemoveNewBackupExtHomeDir begin, type %{public}d, path %{public}s",
812         dirType, bundleBackupDir.c_str());
813     if (bundleBackupDir.empty()) {
814         LOG_W(BMS_TAG_INSTALLD, "RemoveNewBackupExtHomeDir backup dir empty, type  %{public}d", dirType);
815         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
816     }
817     bundleBackupDir = bundleBackupDir.replace(bundleBackupDir.find("%"), 1, std::to_string(userid));
818     if (!InstalldOperator::DeleteDir(bundleBackupDir)) {
819         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed, errno is %{public}d", bundleBackupDir.c_str(), errno);
820         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
821     }
822     return ERR_OK;
823 }
824 
CleanBackupExtHomeDir(const std::string & bundleName,const int userid,DirType dirType)825 static void CleanBackupExtHomeDir(const std::string &bundleName, const int userid, DirType dirType)
826 {
827     std::string bundleBackupDir;
828     GetBackupExtDirByType(bundleBackupDir, bundleName, dirType);
829     LOG_D(BMS_TAG_INSTALLD, "CleanBackupExtHomeDir begin, type %{public}d, path %{public}s",
830         dirType, bundleBackupDir.c_str());
831     if (bundleBackupDir.empty()) {
832         LOG_W(BMS_TAG_INSTALLD, "CleanBackupExtHomeDir backup dir empty, type %{public}d", dirType);
833         return;
834     }
835     bundleBackupDir = bundleBackupDir.replace(bundleBackupDir.find("%"), 1, std::to_string(userid));
836     if (!InstalldOperator::DeleteFiles(bundleBackupDir)) {
837         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed, errno is %{public}d", bundleBackupDir.c_str(), errno);
838     }
839 }
840 
CleanNewBackupExtHomeDir(const std::string & bundleName,const int userid,DirType dirType)841 static void CleanNewBackupExtHomeDir(const std::string &bundleName, const int userid, DirType dirType)
842 {
843     std::string bundleBackupDir;
844     GetNewBackupExtDirByType(bundleBackupDir, bundleName, dirType);
845     LOG_D(BMS_TAG_INSTALLD, "CleanNewBackupExtHomeDir begin, type %{public}d, path %{public}s",
846         dirType, bundleBackupDir.c_str());
847     if (bundleBackupDir.empty()) {
848         LOG_W(BMS_TAG_INSTALLD, "CleanNewBackupExtHomeDir backup dir empty, type %{public}d", dirType);
849         return;
850     }
851     bundleBackupDir = bundleBackupDir.replace(bundleBackupDir.find("%"), 1, std::to_string(userid));
852     if (!InstalldOperator::DeleteFiles(bundleBackupDir)) {
853         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed, errno is %{public}d", bundleBackupDir.c_str(), errno);
854     }
855 }
856 
RemoveDistributedDir(const std::string & bundleName,const int userid)857 static ErrCode RemoveDistributedDir(const std::string &bundleName, const int userid)
858 {
859     std::string distributedFile = DISTRIBUTED_FILE + bundleName;
860     distributedFile = distributedFile.replace(distributedFile.find("%"), 1, std::to_string(userid));
861     if (!InstalldOperator::DeleteDir(distributedFile)) {
862         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed, errno is %{public}d", distributedFile.c_str(), errno);
863         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
864     }
865     std::string fileNonAccount = DISTRIBUTED_FILE_NON_ACCOUNT + bundleName;
866     fileNonAccount = fileNonAccount.replace(fileNonAccount.find("%"), 1, std::to_string(userid));
867     if (!InstalldOperator::DeleteDir(fileNonAccount)) {
868         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed, errno is %{public}d", fileNonAccount.c_str(), errno);
869         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
870     }
871     return ERR_OK;
872 }
873 
CleanDistributedDir(const std::string & bundleName,const int userid)874 static void CleanDistributedDir(const std::string &bundleName, const int userid)
875 {
876     std::string distributedFile = DISTRIBUTED_FILE + bundleName;
877     distributedFile = distributedFile.replace(distributedFile.find("%"), 1, std::to_string(userid));
878     if (!InstalldOperator::DeleteFiles(distributedFile)) {
879         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed, errno is %{public}d", distributedFile.c_str(), errno);
880     }
881     std::string fileNonAccount = DISTRIBUTED_FILE_NON_ACCOUNT + bundleName;
882     fileNonAccount = fileNonAccount.replace(fileNonAccount.find("%"), 1, std::to_string(userid));
883     if (!InstalldOperator::DeleteFiles(fileNonAccount)) {
884         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed, errno is %{public}d", fileNonAccount.c_str(), errno);
885     }
886 }
887 
RemoveShareDir(const std::string & bundleName,const int userid)888 static ErrCode RemoveShareDir(const std::string &bundleName, const int userid)
889 {
890     std::string shareFileDir = SHARE_FILE_PATH + bundleName;
891     shareFileDir = shareFileDir.replace(shareFileDir.find("%"), 1, std::to_string(userid));
892     if (!InstalldOperator::DeleteDir(shareFileDir)) {
893         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", shareFileDir.c_str(), errno);
894         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
895     }
896     return ERR_OK;
897 }
898 
CleanShareDir(const std::string & bundleName,const int userid)899 static void CleanShareDir(const std::string &bundleName, const int userid)
900 {
901     std::string shareFileDir = SHARE_FILE_PATH + bundleName;
902     shareFileDir = shareFileDir.replace(shareFileDir.find("%"), 1, std::to_string(userid));
903     if (!InstalldOperator::DeleteFiles(shareFileDir)) {
904         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", shareFileDir.c_str(), errno);
905     }
906 }
907 
RemoveCloudDir(const std::string & bundleName,const int userid)908 static ErrCode RemoveCloudDir(const std::string &bundleName, const int userid)
909 {
910     std::string cloudFileDir = CLOUD_FILE_PATH + bundleName;
911     cloudFileDir = cloudFileDir.replace(cloudFileDir.find("%"), 1, std::to_string(userid));
912     if (!InstalldOperator::DeleteDir(cloudFileDir)) {
913         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", cloudFileDir.c_str(), errno);
914         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
915     }
916     return ERR_OK;
917 }
918 
CleanCloudDir(const std::string & bundleName,const int userid)919 static void CleanCloudDir(const std::string &bundleName, const int userid)
920 {
921     std::string cloudFileDir = CLOUD_FILE_PATH + bundleName;
922     cloudFileDir = cloudFileDir.replace(cloudFileDir.find("%"), 1, std::to_string(userid));
923     if (!InstalldOperator::DeleteFiles(cloudFileDir)) {
924         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", cloudFileDir.c_str(), errno);
925     }
926 }
927 
CleanBundleDataForEl2(const std::string & bundleName,const int userid,const int appIndex)928 static void CleanBundleDataForEl2(const std::string &bundleName, const int userid, const int appIndex)
929 {
930     std::string suffixName = bundleName;
931     if (appIndex > 0) {
932         suffixName = BundleCloneCommonHelper::GetCloneDataDir(bundleName, appIndex);
933     }
934     std::string dataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + ServiceConstants::BUNDLE_EL[1] +
935         ServiceConstants::PATH_SEPARATOR + std::to_string(userid);
936     std::string databaseDir = dataDir + ServiceConstants::DATABASE + suffixName;
937     if (!InstalldOperator::DeleteFiles(databaseDir)) {
938         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", databaseDir.c_str(), errno);
939     }
940     std::string logDir = dataDir + ServiceConstants::LOG + suffixName;
941     if (!InstalldOperator::DeleteFiles(logDir)) {
942         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", logDir.c_str(), errno);
943     }
944     std::string bundleDataDir = dataDir + ServiceConstants::BASE + suffixName;
945     for (const auto &dir : BUNDLE_DATA_DIR) {
946         std::string subDir = bundleDataDir + dir;
947         if (!InstalldOperator::DeleteFiles(subDir)) {
948             LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", subDir.c_str(), errno);
949         }
950     }
951     if (!InstalldOperator::DeleteFilesExceptDirs(bundleDataDir, BUNDLE_DATA_DIR)) {
952         LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", bundleDataDir.c_str(), errno);
953     }
954 }
955 
RemoveBundleDataDir(const std::string & bundleName,const int32_t userId,bool isAtomicService,const bool async)956 ErrCode InstalldHostImpl::RemoveBundleDataDir(const std::string &bundleName, const int32_t userId,
957     bool isAtomicService, const bool async)
958 {
959     LOG_D(BMS_TAG_INSTALLD, "InstalldHostImpl::RemoveBundleDataDir bundleName:%{public}s", bundleName.c_str());
960     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
961         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
962         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
963     }
964     if (bundleName.empty() || userId < 0) {
965         LOG_E(BMS_TAG_INSTALLD, "Calling the function CreateBundleDataDir with invalid param");
966         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
967     }
968     if (isAtomicService) {
969         LOG_I(BMS_TAG_INSTALLD, "bundleName:%{public}s is atomic service, need process", bundleName.c_str());
970         return InnerRemoveAtomicServiceBundleDataDir(bundleName, userId, async);
971     }
972 
973     ErrCode result = InnerRemoveBundleDataDir(bundleName, userId, async);
974     if (result != ERR_OK) {
975         return InnerRemoveBundleDataDir(bundleName, userId, async);
976     }
977     return ERR_OK;
978 }
979 
RemoveModuleDataDir(const std::string & ModuleDir,const int userid)980 ErrCode InstalldHostImpl::RemoveModuleDataDir(const std::string &ModuleDir, const int userid)
981 {
982     LOG_D(BMS_TAG_INSTALLD, "InstalldHostImpl::RemoveModuleDataDir ModuleDir:%{public}s", ModuleDir.c_str());
983     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
984         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
985         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
986     }
987     if (ModuleDir.empty() || userid < 0) {
988         LOG_E(BMS_TAG_INSTALLD, "Calling the function CreateModuleDataDir with invalid param");
989         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
990     }
991 
992     for (const auto &el : ServiceConstants::BUNDLE_EL) {
993         std::string moduleDataDir = GetBundleDataDir(el, userid) + ServiceConstants::BASE + ModuleDir;
994         if (!InstalldOperator::DeleteDir(moduleDataDir)) {
995             LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", moduleDataDir.c_str(), errno);
996         }
997     }
998     return ERR_OK;
999 }
1000 
RemoveDir(const std::string & dir)1001 ErrCode InstalldHostImpl::RemoveDir(const std::string &dir)
1002 {
1003     LOG_D(BMS_TAG_INSTALLD, "InstalldHostImpl::RemoveDir:%{public}s", dir.c_str());
1004     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1005         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1006         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1007     }
1008     if (dir.empty()) {
1009         LOG_E(BMS_TAG_INSTALLD, "Calling the function RemoveDir with invalid param");
1010         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1011     }
1012     if (!InstalldOperator::DeleteDir(dir)) {
1013         LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", dir.c_str(), errno);
1014         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
1015     }
1016     return ERR_OK;
1017 }
1018 
GetDiskUsage(const std::string & dir,bool isRealPath)1019 int64_t InstalldHostImpl::GetDiskUsage(const std::string &dir, bool isRealPath)
1020 {
1021     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1022         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1023         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1024     }
1025 
1026     return InstalldOperator::GetDiskUsage(dir, isRealPath);
1027 }
1028 
GetDiskUsageFromPath(const std::vector<std::string> & path,int64_t & statSize)1029 ErrCode InstalldHostImpl::GetDiskUsageFromPath(const std::vector<std::string> &path, int64_t &statSize)
1030 {
1031     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1032         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1033         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1034     }
1035     statSize = InstalldOperator::GetDiskUsageFromPath(path);
1036     return ERR_OK;
1037 }
1038 
CleanBundleDataDir(const std::string & dataDir)1039 ErrCode InstalldHostImpl::CleanBundleDataDir(const std::string &dataDir)
1040 {
1041     LOG_D(BMS_TAG_INSTALLD, "InstalldHostImpl::CleanBundleDataDir start");
1042     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1043         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1044         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1045     }
1046     if (dataDir.empty()) {
1047         LOG_E(BMS_TAG_INSTALLD, "Calling the function CleanBundleDataDir with invalid param");
1048         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1049     }
1050 
1051     if (!InstalldOperator::DeleteFiles(dataDir)) {
1052         LOG_E(BMS_TAG_INSTALLD, "CleanBundleDataDir delete files failed errno:%{public}d", errno);
1053         return ERR_APPEXECFWK_INSTALLD_CLEAN_DIR_FAILED;
1054     }
1055     return ERR_OK;
1056 }
1057 
CleanBundleDataDirByName(const std::string & bundleName,const int userid,const int appIndex)1058 ErrCode InstalldHostImpl::CleanBundleDataDirByName(const std::string &bundleName, const int userid, const int appIndex)
1059 {
1060     LOG_D(BMS_TAG_INSTALLD,
1061         "InstalldHostImpl::CleanBundleDataDirByName bundleName:%{public}s,userid:%{public}d,appIndex:%{public}d",
1062         bundleName.c_str(), userid, appIndex);
1063     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1064         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1065         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1066     }
1067     if (bundleName.empty() || userid < 0 || appIndex < 0 || appIndex > Constants::INITIAL_SANDBOX_APP_INDEX) {
1068         LOG_E(BMS_TAG_INSTALLD, "Calling the function CleanBundleDataDirByName with invalid param");
1069         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1070     }
1071     std::string suffixName = bundleName;
1072     std::vector<std::string> elPath(ServiceConstants::BUNDLE_EL);
1073     elPath.push_back(ServiceConstants::DIR_EL5);
1074     for (const auto &el : elPath) {
1075         if (el == ServiceConstants::BUNDLE_EL[1]) {
1076             CleanBundleDataForEl2(bundleName, userid, appIndex);
1077             continue;
1078         }
1079         if (appIndex > 0) {
1080             suffixName = BundleCloneCommonHelper::GetCloneDataDir(bundleName, appIndex);
1081         }
1082         std::string bundleDataDir = GetBundleDataDir(el, userid) + ServiceConstants::BASE + suffixName;
1083         if (!InstalldOperator::DeleteFiles(bundleDataDir)) {
1084             LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", bundleDataDir.c_str(), errno);
1085         }
1086         std::string databaseDir = GetBundleDataDir(el, userid) + ServiceConstants::DATABASE + suffixName;
1087         if (!InstalldOperator::DeleteFiles(databaseDir)) {
1088             LOG_W(BMS_TAG_INSTALLD, "clean dir %{public}s failed errno:%{public}d", databaseDir.c_str(), errno);
1089         }
1090     }
1091     CleanShareDir(bundleName, userid);
1092     CleanCloudDir(bundleName, userid);
1093     CleanBackupExtHomeDir(bundleName, userid, DirType::DIR_EL2);
1094     CleanBackupExtHomeDir(bundleName, userid, DirType::DIR_EL1);
1095     CleanNewBackupExtHomeDir(bundleName, userid, DirType::DIR_EL2);
1096     CleanNewBackupExtHomeDir(bundleName, userid, DirType::DIR_EL1);
1097     CleanDistributedDir(bundleName, userid);
1098     return ERR_OK;
1099 }
1100 
GetBundleDataDir(const std::string & el,const int userid) const1101 std::string InstalldHostImpl::GetBundleDataDir(const std::string &el, const int userid) const
1102 {
1103     std::string dataDir = ServiceConstants::BUNDLE_APP_DATA_BASE_DIR +
1104                           el +
1105                           ServiceConstants::PATH_SEPARATOR +
1106                           std::to_string(userid);
1107     return dataDir;
1108 }
1109 
GetAppDataPath(const std::string & bundleName,const std::string & el,const int32_t userId,const int32_t appIndex)1110 std::string InstalldHostImpl::GetAppDataPath(const std::string &bundleName, const std::string &el,
1111     const int32_t userId, const int32_t appIndex)
1112 {
1113     if (appIndex == 0) {
1114         return ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + el + ServiceConstants::PATH_SEPARATOR +
1115             std::to_string(userId) + ServiceConstants::BASE + bundleName;
1116     } else {
1117         std::string innerDataDir = BundleCloneCommonHelper::GetCloneDataDir(bundleName, appIndex);
1118         return ServiceConstants::BUNDLE_APP_DATA_BASE_DIR + el + ServiceConstants::PATH_SEPARATOR +
1119             std::to_string(userId) + ServiceConstants::BASE + innerDataDir;
1120     }
1121 }
1122 
GetAppCacheSize(const std::string & bundleName,const int32_t userId,const int32_t appIndex,const std::vector<std::string> & moduleNameList)1123 int64_t InstalldHostImpl::GetAppCacheSize(const std::string &bundleName,
1124     const int32_t userId, const int32_t appIndex, const std::vector<std::string> &moduleNameList)
1125 {
1126     std::string bundleNameDir = bundleName;
1127     if (appIndex > 0) {
1128         bundleNameDir = BundleCloneCommonHelper::GetCloneDataDir(bundleName, appIndex);
1129     }
1130     std::vector<std::string> cachePaths;
1131     std::vector<std::string> elPath(ServiceConstants::BUNDLE_EL);
1132     elPath.push_back(ServiceConstants::DIR_EL5);
1133     for (const auto &el : elPath) {
1134         cachePaths.push_back(std::string(ServiceConstants::BUNDLE_APP_DATA_BASE_DIR) + el +
1135             ServiceConstants::PATH_SEPARATOR + std::to_string(userId) + ServiceConstants::BASE +
1136             bundleNameDir + ServiceConstants::PATH_SEPARATOR + Constants::CACHE_DIR);
1137         for (const auto &moduleName : moduleNameList) {
1138             std::string moduleCachePath = std::string(ServiceConstants::BUNDLE_APP_DATA_BASE_DIR) + el +
1139                 ServiceConstants::PATH_SEPARATOR + std::to_string(userId) + ServiceConstants::BASE + bundleNameDir +
1140                 ServiceConstants::HAPS + moduleName + ServiceConstants::PATH_SEPARATOR + Constants::CACHE_DIR;
1141             cachePaths.push_back(moduleCachePath);
1142         }
1143     }
1144     return InstalldOperator::GetDiskUsageFromPath(cachePaths);
1145 }
1146 
GetBundleStats(const std::string & bundleName,const int32_t userId,std::vector<int64_t> & bundleStats,const int32_t uid,const int32_t appIndex,const uint32_t statFlag,const std::vector<std::string> & moduleNameList)1147 ErrCode InstalldHostImpl::GetBundleStats(const std::string &bundleName, const int32_t userId,
1148     std::vector<int64_t> &bundleStats, const int32_t uid, const int32_t appIndex,
1149     const uint32_t statFlag, const std::vector<std::string> &moduleNameList)
1150 {
1151     LOG_D(BMS_TAG_INSTALLD,
1152         "GetBundleStats, bundleName = %{public}s, userId = %{public}d, uid = %{public}d, appIndex = %{public}d",
1153         bundleName.c_str(), userId, uid, appIndex);
1154     LOG_D(BMS_TAG_INSTALLD,
1155         "GetBundleStats, statFlag = %{public}d", statFlag);
1156     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1157         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1158         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1159     }
1160     if (bundleName.empty()) {
1161         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1162     }
1163     bundleStats = {0, 0, 0, 0, 0};
1164     std::vector<std::string> bundlePath;
1165     bundlePath.push_back(std::string(Constants::BUNDLE_CODE_DIR) + ServiceConstants::PATH_SEPARATOR + bundleName);
1166     int64_t appDataSize = 0;
1167     int64_t bundleDataSize = 0;
1168     int64_t bundleCacheSize = 0;
1169     if ((statFlag & OHOS::AppExecFwk::Constants::NoGetBundleStatsFlag::GET_BUNDLE_WITHOUT_INSTALL_SIZE) !=
1170         OHOS::AppExecFwk::Constants::NoGetBundleStatsFlag::GET_BUNDLE_WITHOUT_INSTALL_SIZE) {
1171         appDataSize = appIndex == 0 ? InstalldOperator::GetDiskUsageFromPath(bundlePath) : 0;
1172     }
1173     if ((statFlag & OHOS::AppExecFwk::Constants::NoGetBundleStatsFlag::GET_BUNDLE_WITHOUT_DATA_SIZE) !=
1174         OHOS::AppExecFwk::Constants::NoGetBundleStatsFlag::GET_BUNDLE_WITHOUT_DATA_SIZE) {
1175         bundleDataSize = InstalldOperator::GetDiskUsageFromQuota(uid);
1176     }
1177     if ((statFlag & OHOS::AppExecFwk::Constants::GET_BUNDLE_WITHOUT_CACHE_SIZE) !=
1178         OHOS::AppExecFwk::Constants::NoGetBundleStatsFlag::GET_BUNDLE_WITHOUT_CACHE_SIZE) {
1179         bundleCacheSize = GetAppCacheSize(bundleName, userId, appIndex, moduleNameList);
1180     }
1181     // index 0 : bundle data size
1182     bundleStats[0] = appDataSize;
1183     // index 1 : local bundle data size
1184     bundleStats[1] = bundleDataSize;
1185     // index 4 : cache size
1186     bundleStats[4] = bundleCacheSize;
1187     return ERR_OK;
1188 }
1189 
GetAllBundleStats(const int32_t userId,std::vector<int64_t> & bundleStats,const std::vector<int32_t> & uids)1190 ErrCode InstalldHostImpl::GetAllBundleStats(const int32_t userId,
1191     std::vector<int64_t> &bundleStats, const std::vector<int32_t> &uids)
1192 {
1193     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1194         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1195         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1196     }
1197     if (uids.empty()) {
1198         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1199     }
1200     int64_t totalFileSize = InstalldOperator::GetDiskUsageFromQuota(INSTALLS_UID);
1201     int64_t totalDataSize = 0;
1202     for (size_t index = 0; index < uids.size(); ++index) {
1203         const auto &uid = uids[index];
1204         int64_t bundleDataSize = InstalldOperator::GetDiskUsageFromQuota(uid);
1205         // index 1 : local bundle data size
1206         totalDataSize += bundleDataSize;
1207     }
1208     bundleStats.push_back(totalFileSize);
1209     bundleStats.push_back(totalDataSize);
1210     bundleStats.push_back(0);
1211     bundleStats.push_back(0);
1212     bundleStats.push_back(0);
1213     return ERR_OK;
1214 }
1215 
GetHapFlags(const bool isPreInstallApp,const bool debug,const bool isDlpSandbox)1216 unsigned int InstalldHostImpl::GetHapFlags(const bool isPreInstallApp, const bool debug, const bool isDlpSandbox)
1217 {
1218     unsigned int hapFlags = 0;
1219 #ifdef WITH_SELINUX
1220     hapFlags = isPreInstallApp ? SELINUX_HAP_RESTORECON_PREINSTALLED_APP : 0;
1221     hapFlags |= debug ? SELINUX_HAP_DEBUGGABLE : 0;
1222     hapFlags |= isDlpSandbox ? SELINUX_HAP_DLP : 0;
1223 #endif
1224     return hapFlags;
1225 }
1226 
SetDirApl(const std::string & dir,const std::string & bundleName,const std::string & apl,bool isPreInstallApp,bool debug)1227 ErrCode InstalldHostImpl::SetDirApl(const std::string &dir, const std::string &bundleName, const std::string &apl,
1228     bool isPreInstallApp, bool debug)
1229 {
1230     unsigned int hapFlags = GetHapFlags(isPreInstallApp, debug, false);
1231     return SetDirApl(dir, bundleName, apl, hapFlags);
1232 }
1233 
SetDirApl(const std::string & dir,const std::string & bundleName,const std::string & apl,unsigned int hapFlags)1234 ErrCode InstalldHostImpl::SetDirApl(const std::string &dir, const std::string &bundleName, const std::string &apl,
1235     unsigned int hapFlags)
1236 {
1237 #ifdef WITH_SELINUX
1238     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1239         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1240         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1241     }
1242     if (dir.empty() || bundleName.empty()) {
1243         LOG_E(BMS_TAG_INSTALLD, "Calling the function SetDirApl with invalid param");
1244         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1245     }
1246     HapFileInfo hapFileInfo;
1247     hapFileInfo.pathNameOrig.push_back(dir);
1248     hapFileInfo.apl = apl;
1249     hapFileInfo.packageName = bundleName;
1250     hapFileInfo.flags = SELINUX_HAP_RESTORECON_RECURSE;
1251     hapFileInfo.hapFlags = hapFlags;
1252     HapContext hapContext;
1253     int ret = hapContext.HapFileRestorecon(hapFileInfo);
1254     if (ret != 0) {
1255         LOG_E(BMS_TAG_INSTALLD, "HapFileRestorecon path: %{public}s failed, apl: %{public}s, errcode:%{public}d",
1256             dir.c_str(), apl.c_str(), ret);
1257         return ERR_APPEXECFWK_INSTALLD_SET_SELINUX_LABEL_FAILED;
1258     }
1259     return ret;
1260 #else
1261     return ERR_OK;
1262 #endif // WITH_SELINUX
1263 }
1264 
GetBundleCachePath(const std::string & dir,std::vector<std::string> & cachePath)1265 ErrCode InstalldHostImpl::GetBundleCachePath(const std::string &dir, std::vector<std::string> &cachePath)
1266 {
1267     LOG_D(BMS_TAG_INSTALLD, "InstalldHostImpl::GetBundleCachePath start");
1268     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1269         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1270         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1271     }
1272     if (dir.empty()) {
1273         LOG_E(BMS_TAG_INSTALLD, "Calling the function GetBundleCachePath with invalid param");
1274         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1275     }
1276     InstalldOperator::TraverseCacheDirectory(dir, cachePath);
1277     return ERR_OK;
1278 }
1279 
ScanDir(const std::string & dir,ScanMode scanMode,ResultMode resultMode,std::vector<std::string> & paths)1280 ErrCode InstalldHostImpl::ScanDir(
1281     const std::string &dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &paths)
1282 {
1283     LOG_D(BMS_TAG_INSTALLD, "InstalldHostImpl::Scan start %{public}s", dir.c_str());
1284     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1285         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1286         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1287     }
1288     if (dir.empty()) {
1289         LOG_E(BMS_TAG_INSTALLD, "Calling the function Scan with invalid param");
1290         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1291     }
1292 
1293     InstalldOperator::ScanDir(dir, scanMode, resultMode, paths);
1294     return ERR_OK;
1295 }
1296 
MoveFile(const std::string & oldPath,const std::string & newPath)1297 ErrCode InstalldHostImpl::MoveFile(const std::string &oldPath, const std::string &newPath)
1298 {
1299     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1300         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1301         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1302     }
1303     if (!InstalldOperator::MoveFile(oldPath, newPath)) {
1304         LOG_E(BMS_TAG_INSTALLD, "Move file %{public}s to %{public}s failed errno:%{public}d",
1305             oldPath.c_str(), newPath.c_str(), errno);
1306         return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
1307     }
1308     return ERR_OK;
1309 }
1310 
CopyFile(const std::string & oldPath,const std::string & newPath,const std::string & signatureFilePath)1311 ErrCode InstalldHostImpl::CopyFile(const std::string &oldPath, const std::string &newPath,
1312     const std::string &signatureFilePath)
1313 {
1314     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1315         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1316         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1317     }
1318     if (!InstalldOperator::CopyFileFast(oldPath, newPath)) {
1319         LOG_E(BMS_TAG_INSTALLD, "Copy file %{public}s to %{public}s failed errno:%{public}d",
1320             oldPath.c_str(), newPath.c_str(), errno);
1321         return ERR_APPEXECFWK_INSTALLD_COPY_FILE_FAILED;
1322     }
1323     mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
1324     if (!OHOS::ChangeModeFile(newPath, mode)) {
1325         LOG_E(BMS_TAG_INSTALLD, "change mode failed");
1326         return ERR_APPEXECFWK_INSTALLD_COPY_FILE_FAILED;
1327     }
1328 
1329     if (signatureFilePath.empty()) {
1330         LOG_D(BMS_TAG_INSTALLD, "signature file path is empty and no need to process code signature");
1331         return ERR_OK;
1332     }
1333 
1334 #if defined(CODE_SIGNATURE_ENABLE)
1335     Security::CodeSign::EntryMap entryMap = {{ ServiceConstants::CODE_SIGNATURE_HAP, newPath }};
1336     ErrCode ret = Security::CodeSign::CodeSignUtils::EnforceCodeSignForApp(entryMap, signatureFilePath);
1337     if (ret != ERR_OK) {
1338         LOG_E(BMS_TAG_INSTALLD, "hap or hsp code signature failed due to %{public}d", ret);
1339         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
1340     }
1341 #endif
1342     return ERR_OK;
1343 }
1344 
Mkdir(const std::string & dir,const int32_t mode,const int32_t uid,const int32_t gid)1345 ErrCode InstalldHostImpl::Mkdir(
1346     const std::string &dir, const int32_t mode, const int32_t uid, const int32_t gid)
1347 {
1348     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1349         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1350         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1351     }
1352     LOG_D(BMS_TAG_INSTALLD, "Mkdir start %{public}s", dir.c_str());
1353     if (dir.empty()) {
1354         LOG_E(BMS_TAG_INSTALLD, "Calling the function Mkdir with invalid param");
1355         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1356     }
1357 
1358     if (!InstalldOperator::MkOwnerDir(dir, mode, uid, gid)) {
1359         LOG_E(BMS_TAG_INSTALLD, "Mkdir %{public}s failed errno:%{public}d", dir.c_str(), errno);
1360         return ERR_APPEXECFWK_INSTALLD_MKDIR_FAILED;
1361     }
1362 
1363     return ERR_OK;
1364 }
1365 
GetFileStat(const std::string & file,FileStat & fileStat)1366 ErrCode InstalldHostImpl::GetFileStat(const std::string &file, FileStat &fileStat)
1367 {
1368     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1369         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1370         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1371     }
1372 
1373     LOG_D(BMS_TAG_INSTALLD, "GetFileStat start %{public}s", file.c_str());
1374     struct stat s;
1375     if (stat(file.c_str(), &s) != 0) {
1376         LOG_E(BMS_TAG_INSTALLD, "Stat file(%{public}s) failed", file.c_str());
1377         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1378     }
1379 
1380     fileStat.uid = static_cast<int32_t>(s.st_uid);
1381     fileStat.gid = static_cast<int32_t>(s.st_gid);
1382     fileStat.lastModifyTime = static_cast<int64_t>(s.st_mtime);
1383     fileStat.isDir = s.st_mode & S_IFDIR;
1384     fileStat.mode = static_cast<int32_t>(s.st_mode);
1385     return ERR_OK;
1386 }
1387 
ExtractDiffFiles(const std::string & filePath,const std::string & targetPath,const std::string & cpuAbi)1388 ErrCode InstalldHostImpl::ExtractDiffFiles(const std::string &filePath, const std::string &targetPath,
1389     const std::string &cpuAbi)
1390 {
1391     if (filePath.empty() || targetPath.empty()) {
1392         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractDiffFiles with invalid param");
1393         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1394     }
1395     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1396         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1397         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1398     }
1399     if (!InstalldOperator::ExtractDiffFiles(filePath, targetPath, cpuAbi)) {
1400         LOG_E(BMS_TAG_INSTALLD, "fail to ExtractDiffFiles errno:%{public}d", errno);
1401         return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
1402     }
1403     return ERR_OK;
1404 }
1405 
ApplyDiffPatch(const std::string & oldSoPath,const std::string & diffFilePath,const std::string & newSoPath,int32_t uid)1406 ErrCode InstalldHostImpl::ApplyDiffPatch(const std::string &oldSoPath, const std::string &diffFilePath,
1407     const std::string &newSoPath, int32_t uid)
1408 {
1409     if (oldSoPath.empty() || diffFilePath.empty() || newSoPath.empty()) {
1410         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractDiffFiles with invalid param");
1411         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1412     }
1413     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1414         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1415         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1416     }
1417     if (!InstalldOperator::ApplyDiffPatch(oldSoPath, diffFilePath, newSoPath, uid)) {
1418         LOG_E(BMS_TAG_INSTALLD, "fail to ApplyDiffPatch errno:%{public}d", errno);
1419         return ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED;
1420     }
1421     return ERR_OK;
1422 }
1423 
IsExistDir(const std::string & dir,bool & isExist)1424 ErrCode InstalldHostImpl::IsExistDir(const std::string &dir, bool &isExist)
1425 {
1426     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1427         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1428         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1429     }
1430     isExist = InstalldOperator::IsExistDir(dir);
1431     return ERR_OK;
1432 }
1433 
IsExistFile(const std::string & path,bool & isExist)1434 ErrCode InstalldHostImpl::IsExistFile(const std::string &path, bool &isExist)
1435 {
1436     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1437         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1438         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1439     }
1440     isExist = InstalldOperator::IsExistFile(path);
1441     return ERR_OK;
1442 }
1443 
IsExistApFile(const std::string & path,bool & isExist)1444 ErrCode InstalldHostImpl::IsExistApFile(const std::string &path, bool &isExist)
1445 {
1446     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1447         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1448         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1449     }
1450     isExist = InstalldOperator::IsExistApFile(path);
1451     return ERR_OK;
1452 }
1453 
IsDirEmpty(const std::string & dir,bool & isDirEmpty)1454 ErrCode InstalldHostImpl::IsDirEmpty(const std::string &dir, bool &isDirEmpty)
1455 {
1456     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1457         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1458         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1459     }
1460     isDirEmpty = InstalldOperator::IsDirEmpty(dir);
1461     return ERR_OK;
1462 }
1463 
ObtainQuickFixFileDir(const std::string & dir,std::vector<std::string> & dirVec)1464 ErrCode InstalldHostImpl::ObtainQuickFixFileDir(const std::string &dir, std::vector<std::string> &dirVec)
1465 {
1466     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1467         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1468         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1469     }
1470     InstalldOperator::ObtainQuickFixFileDir(dir, dirVec);
1471     return ERR_OK;
1472 }
1473 
CopyFiles(const std::string & sourceDir,const std::string & destinationDir)1474 ErrCode InstalldHostImpl::CopyFiles(const std::string &sourceDir, const std::string &destinationDir)
1475 {
1476     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1477         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1478         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1479     }
1480 
1481     InstalldOperator::CopyFiles(sourceDir, destinationDir);
1482     return ERR_OK;
1483 }
1484 
GetNativeLibraryFileNames(const std::string & filePath,const std::string & cpuAbi,std::vector<std::string> & fileNames)1485 ErrCode InstalldHostImpl::GetNativeLibraryFileNames(const std::string &filePath, const std::string &cpuAbi,
1486     std::vector<std::string> &fileNames)
1487 {
1488     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1489         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1490         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1491     }
1492     if (filePath.empty()) {
1493         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractDiffFiles with invalid param");
1494         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1495     }
1496     InstalldOperator::GetNativeLibraryFileNames(filePath, cpuAbi, fileNames);
1497     return ERR_OK;
1498 }
1499 
VerifyCodeSignature(const CodeSignatureParam & codeSignatureParam)1500 ErrCode InstalldHostImpl::VerifyCodeSignature(const CodeSignatureParam &codeSignatureParam)
1501 {
1502     LOG_D(BMS_TAG_INSTALLD, "start to process the code signature for so files");
1503     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1504         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1505         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1506     }
1507     LOG_D(BMS_TAG_INSTALLD, "code sign param is %{public}s", codeSignatureParam.ToString().c_str());
1508     if (codeSignatureParam.modulePath.empty()) {
1509         LOG_E(BMS_TAG_INSTALLD, "Calling the function VerifyCodeSignature with invalid param");
1510         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1511     }
1512     if (!InstalldOperator::VerifyCodeSignature(codeSignatureParam)) {
1513         LOG_E(BMS_TAG_INSTALLD, "verify code signature failed");
1514         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
1515     }
1516     return ERR_OK;
1517 }
1518 
CheckEncryption(const CheckEncryptionParam & checkEncryptionParam,bool & isEncryption)1519 ErrCode InstalldHostImpl::CheckEncryption(const CheckEncryptionParam &checkEncryptionParam, bool &isEncryption)
1520 {
1521     LOG_D(BMS_TAG_INSTALLD, "start to process check encryption");
1522     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1523         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1524         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1525     }
1526 
1527     if (checkEncryptionParam.modulePath.empty()) {
1528         LOG_E(BMS_TAG_INSTALLD, "Calling the function CheckEncryption with invalid param");
1529         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1530     }
1531     if (!InstalldOperator::CheckEncryption(checkEncryptionParam, isEncryption)) {
1532         LOG_E(BMS_TAG_INSTALLD, "check encryption failed");
1533         return ERR_APPEXECFWK_INSTALL_CHECK_ENCRYPTION_FAILED;
1534     }
1535     return ERR_OK;
1536 }
1537 
MoveFiles(const std::string & srcDir,const std::string & desDir)1538 ErrCode InstalldHostImpl::MoveFiles(const std::string &srcDir, const std::string &desDir)
1539 {
1540     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1541         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1542         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1543     }
1544 
1545     if (srcDir.empty() || desDir.empty()) {
1546         LOG_E(BMS_TAG_INSTALLD, "Calling the function MoveFiles with invalid param");
1547         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1548     }
1549     if (!InstalldOperator::MoveFiles(srcDir, desDir)) {
1550         LOG_E(BMS_TAG_INSTALLD, "move files failed errno:%{public}d", errno);
1551         return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
1552     }
1553     return ERR_OK;
1554 }
1555 
ExtractDriverSoFiles(const std::string & srcPath,const std::unordered_multimap<std::string,std::string> & dirMap)1556 ErrCode InstalldHostImpl::ExtractDriverSoFiles(const std::string &srcPath,
1557     const std::unordered_multimap<std::string, std::string> &dirMap)
1558 {
1559     LOG_D(BMS_TAG_INSTALLD, "start to copy driver so files");
1560     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1561         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1562         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1563     }
1564     if (dirMap.empty()) {
1565         LOG_E(BMS_TAG_INSTALLD, "Calling the function ExtractDriverSoFiles with invalid param");
1566         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1567     }
1568 
1569     if (!InstalldOperator::ExtractDriverSoFiles(srcPath, dirMap)) {
1570         LOG_E(BMS_TAG_INSTALLD, "copy driver so files failed errno:%{public}d", errno);
1571         return ERR_APPEXECFWK_INSTALLD_COPY_FILE_FAILED;
1572     }
1573     return ERR_OK;
1574 }
1575 
ExtractEncryptedSoFiles(const std::string & hapPath,const std::string & realSoFilesPath,const std::string & cpuAbi,const std::string & tmpSoPath,int32_t uid)1576 ErrCode InstalldHostImpl::ExtractEncryptedSoFiles(const std::string &hapPath, const std::string &realSoFilesPath,
1577     const std::string &cpuAbi, const std::string &tmpSoPath, int32_t uid)
1578 {
1579     LOG_D(BMS_TAG_INSTALLD, "start to obtain decoded so files");
1580 #if defined(CODE_ENCRYPTION_ENABLE)
1581     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1582         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1583         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1584     }
1585 
1586     if (hapPath.empty() || tmpSoPath.empty()) {
1587         LOG_E(BMS_TAG_INSTALLD, "hapPath %{public}s or tmpSoPath %{public}s is empty",
1588             hapPath.c_str(), tmpSoPath.c_str());
1589         return ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATH;
1590     }
1591 
1592     if (!CheckPathValid(hapPath, Constants::BUNDLE_CODE_DIR) ||
1593         !CheckPathValid(realSoFilesPath, Constants::BUNDLE_CODE_DIR) ||
1594         !CheckPathValid(tmpSoPath, ServiceConstants::HAP_COPY_PATH)) {
1595         return ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATH;
1596     }
1597     if (realSoFilesPath.empty()) {
1598         /* obtain the decoded so files from hapPath*/
1599         return InstalldOperator::ExtractSoFilesToTmpHapPath(hapPath, cpuAbi, tmpSoPath, uid);
1600     } else {
1601         /* obtain the decoded so files from realSoFilesPath*/
1602         return InstalldOperator::ExtractSoFilesToTmpSoPath(hapPath, realSoFilesPath, cpuAbi, tmpSoPath, uid);
1603     }
1604 #else
1605     LOG_D(BMS_TAG_INSTALLD, "code encryption is not supported");
1606     return ERR_BUNDLEMANAGER_QUICK_FIX_NOT_SUPPORT_CODE_ENCRYPTION;
1607 #endif
1608 }
1609 
1610 #if defined(CODE_SIGNATURE_ENABLE)
PrepareEntryMap(const CodeSignatureParam & codeSignatureParam,Security::CodeSign::EntryMap & entryMap)1611 ErrCode InstalldHostImpl::PrepareEntryMap(const CodeSignatureParam &codeSignatureParam,
1612     Security::CodeSign::EntryMap &entryMap)
1613 {
1614     LOG_D(BMS_TAG_INSTALLD, "PrepareEntryMap target so path is %{public}s", codeSignatureParam.targetSoPath.c_str());
1615     if (codeSignatureParam.modulePath.empty()) {
1616         LOG_E(BMS_TAG_INSTALLD, "real path of the installed hap is empty");
1617         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1618     }
1619     if (codeSignatureParam.targetSoPath.empty()) {
1620         LOG_W(BMS_TAG_INSTALLD, "target so path is empty");
1621         return ERR_OK;
1622     }
1623     std::vector<std::string> fileNames;
1624     if (!InstalldOperator::GetNativeLibraryFileNames(
1625         codeSignatureParam.modulePath, codeSignatureParam.cpuAbi, fileNames)) {
1626         LOG_E(BMS_TAG_INSTALLD, "get native library file names failed");
1627         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
1628     }
1629     const std::string prefix = ServiceConstants::LIBS + codeSignatureParam.cpuAbi + ServiceConstants::PATH_SEPARATOR;
1630     for (const auto &fileName : fileNames) {
1631         std::string entryName = prefix + fileName;
1632         std::string path = codeSignatureParam.targetSoPath;
1633         if (path.back() != ServiceConstants::FILE_SEPARATOR_CHAR) {
1634             path += ServiceConstants::FILE_SEPARATOR_CHAR;
1635         }
1636         entryMap.emplace(entryName, path + fileName);
1637         LOG_D(BMS_TAG_INSTALLD, "entryMap add soEntry %{public}s: %{public}s",
1638             entryName.c_str(), (path + fileName).c_str());
1639     }
1640     return ERR_OK;
1641 }
1642 #endif
1643 
VerifyCodeSignatureForHap(const CodeSignatureParam & codeSignatureParam)1644 ErrCode InstalldHostImpl::VerifyCodeSignatureForHap(const CodeSignatureParam &codeSignatureParam)
1645 {
1646     LOG_D(BMS_TAG_INSTALLD, "code sign param is %{public}s", codeSignatureParam.ToString().c_str());
1647 #if defined(CODE_SIGNATURE_ENABLE)
1648     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1649         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1650         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1651     }
1652     ErrCode ret = ERR_OK;
1653     if (codeSignatureParam.isCompileSdkOpenHarmony && !Security::CodeSign::CodeSignUtils::IsSupportOHCodeSign()) {
1654         LOG_D(BMS_TAG_INSTALLD, "code signature is not supported");
1655         return ret;
1656     }
1657     Security::CodeSign::EntryMap entryMap;
1658     if ((ret = PrepareEntryMap(codeSignatureParam, entryMap)) != ERR_OK) {
1659         LOG_E(BMS_TAG_INSTALLD, "prepare entry map failed");
1660         return ret;
1661     }
1662     if (codeSignatureParam.signatureFileDir.empty()) {
1663         std::shared_ptr<CodeSignHelper> codeSignHelper = std::make_shared<CodeSignHelper>();
1664         Security::CodeSign::FileType fileType = codeSignatureParam.isPreInstalledBundle ?
1665             FILE_ENTRY_ONLY : FILE_ALL;
1666         if (codeSignatureParam.isEnterpriseBundle) {
1667             LOG_D(BMS_TAG_INSTALLD, "Verify code signature for enterprise bundle");
1668             ret = codeSignHelper->EnforceCodeSignForAppWithOwnerId(codeSignatureParam.appIdentifier,
1669                 codeSignatureParam.modulePath, entryMap, fileType);
1670         } else if (codeSignatureParam.isInternaltestingBundle) {
1671             LOG_D(BMS_TAG_INSTALLD, "Verify code signature for internaltesting bundle");
1672             ret = codeSignHelper->EnforceCodeSignForAppWithOwnerId(codeSignatureParam.appIdentifier,
1673                 codeSignatureParam.modulePath, entryMap, fileType);
1674         } else {
1675             LOG_D(BMS_TAG_INSTALLD, "Verify code signature for non-enterprise bundle");
1676             ret = codeSignHelper->EnforceCodeSignForApp(codeSignatureParam.modulePath, entryMap, fileType);
1677         }
1678         LOG_I(BMS_TAG_INSTALLD, "Verify code signature %{public}s", codeSignatureParam.modulePath.c_str());
1679     } else {
1680         LOG_D(BMS_TAG_INSTALLD, "Verify code signature with: %{public}s", codeSignatureParam.signatureFileDir.c_str());
1681         ret = Security::CodeSign::CodeSignUtils::EnforceCodeSignForApp(entryMap, codeSignatureParam.signatureFileDir);
1682     }
1683     if (ret != ERR_OK) {
1684         LOG_E(BMS_TAG_INSTALLD, "hap or hsp code signature failed due to %{public}d", ret);
1685         return ERR_BUNDLEMANAGER_INSTALL_CODE_SIGNATURE_FAILED;
1686     }
1687 #else
1688     LOG_W(BMS_TAG_INSTALLD, "code signature feature is not supported");
1689 #endif
1690     return ERR_OK;
1691 }
1692 
DeliverySignProfile(const std::string & bundleName,int32_t profileBlockLength,const unsigned char * profileBlock)1693 ErrCode InstalldHostImpl::DeliverySignProfile(const std::string &bundleName, int32_t profileBlockLength,
1694     const unsigned char *profileBlock)
1695 {
1696     LOG_D(BMS_TAG_INSTALLD, "start to delivery sign profile");
1697 #if defined(CODE_SIGNATURE_ENABLE)
1698     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1699         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1700         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1701     }
1702 
1703     if (bundleName.empty() || profileBlock == nullptr || profileBlockLength == 0) {
1704         LOG_E(BMS_TAG_INSTALLD, "Calling the function DeliverySignProfile with invalid param");
1705         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1706     }
1707 
1708     LOG_D(BMS_TAG_INSTALLD, "delivery profile of bundle %{public}s and profile size is %{public}d", bundleName.c_str(),
1709         profileBlockLength);
1710     Security::CodeSign::ByteBuffer byteBuffer;
1711     byteBuffer.CopyFrom(reinterpret_cast<const uint8_t *>(profileBlock), profileBlockLength);
1712     ErrCode ret = Security::CodeSign::CodeSignUtils::EnableKeyInProfile(bundleName, byteBuffer);
1713     if (ret != ERR_OK) {
1714         LOG_E(BMS_TAG_INSTALLD, "delivery code sign profile failed due to error %{public}d", ret);
1715         return ERR_BUNDLE_MANAGER_CODE_SIGNATURE_DELIVERY_FILE_FAILED;
1716     }
1717 #else
1718     LOG_W(BMS_TAG_INSTALLD, "code signature feature is not supported");
1719 #endif
1720     return ERR_OK;
1721 }
1722 
RemoveSignProfile(const std::string & bundleName)1723 ErrCode InstalldHostImpl::RemoveSignProfile(const std::string &bundleName)
1724 {
1725     LOG_D(BMS_TAG_INSTALLD, "start to remove sign profile");
1726 #if defined(CODE_SIGNATURE_ENABLE)
1727     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1728         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1729         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1730     }
1731 
1732     if (bundleName.empty()) {
1733         LOG_E(BMS_TAG_INSTALLD, "Calling the function RemoveSignProfile with invalid param");
1734         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1735     }
1736 
1737     ErrCode ret = Security::CodeSign::CodeSignUtils::RemoveKeyInProfile(bundleName);
1738     if (ret != ERR_OK) {
1739         LOG_E(BMS_TAG_INSTALLD, "remove code sign profile failed due to error %{public}d", ret);
1740         return ERR_BUNDLE_MANAGER_CODE_SIGNATURE_REMOVE_FILE_FAILED;
1741     }
1742 #else
1743     LOG_W(BMS_TAG_INSTALLD, "code signature feature is not supported");
1744 #endif
1745     return ERR_OK;
1746 }
1747 
CheckPathValid(const std::string & path,const std::string & prefix)1748 bool InstalldHostImpl::CheckPathValid(const std::string &path, const std::string &prefix)
1749 {
1750     if (path.empty()) {
1751         return true;
1752     }
1753     if (path.find(ServiceConstants::RELATIVE_PATH) != std::string::npos) {
1754         LOG_E(BMS_TAG_INSTALLD, "path(%{public}s) contain relevant path", path.c_str());
1755         return false;
1756     }
1757     if (path.find(prefix) == std::string::npos) {
1758         LOG_E(BMS_TAG_INSTALLD, "prefix(%{public}s) cannot be found", prefix.c_str());
1759         return false;
1760     }
1761     return true;
1762 }
1763 
SetEncryptionPolicy(int32_t uid,const std::string & bundleName,const int32_t userId,std::string & keyId)1764 ErrCode InstalldHostImpl::SetEncryptionPolicy(int32_t uid, const std::string &bundleName,
1765     const int32_t userId, std::string &keyId)
1766 {
1767     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1768         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1769         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1770     }
1771     if (bundleName.empty()) {
1772         LOG_E(BMS_TAG_INSTALLD, "Calling the function SetEncryptionPolicy with invalid param");
1773         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1774     }
1775     if (!InstalldOperator::GenerateKeyIdAndSetPolicy(uid, bundleName, userId, keyId)) {
1776         LOG_E(BMS_TAG_INSTALLD, "EncryptionPaths fail");
1777         return ERR_APPEXECFWK_INSTALLD_GENERATE_KEY_FAILED;
1778     }
1779     return ERR_OK;
1780 }
1781 
DeleteEncryptionKeyId(const std::string & bundleName,const int32_t userId)1782 ErrCode InstalldHostImpl::DeleteEncryptionKeyId(const std::string &bundleName, const int32_t userId)
1783 {
1784     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1785         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1786         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1787     }
1788     if (bundleName.empty()) {
1789         LOG_E(BMS_TAG_INSTALLD, "Calling the function DeleteEncryptionKeyId with invalid param");
1790         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1791     }
1792     if (!InstalldOperator::DeleteKeyId(bundleName, userId)) {
1793         LOG_E(BMS_TAG_INSTALLD, "EncryptionPaths fail");
1794         return ERR_APPEXECFWK_INSTALLD_DELETE_KEY_FAILED;
1795     }
1796     return ERR_OK;
1797 }
1798 
RemoveExtensionDir(int32_t userId,const std::vector<std::string> & extensionBundleDirs)1799 ErrCode InstalldHostImpl::RemoveExtensionDir(int32_t userId, const std::vector<std::string> &extensionBundleDirs)
1800 {
1801     LOG_I(BMS_TAG_INSTALLD, "RemoveExtensionDir userId: %{public}d, extensionBundleDir size: %{public}zu",
1802         userId, extensionBundleDirs.size());
1803     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1804         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1805         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1806     }
1807     if (extensionBundleDirs.empty() || userId < 0) {
1808         LOG_E(BMS_TAG_INSTALLD, "Calling the function RemoveExtensionDir with invalid param");
1809         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1810     }
1811 
1812     for (const std::string &extensionBundleDir : extensionBundleDirs) {
1813         if (extensionBundleDir.empty()) {
1814             LOG_E(BMS_TAG_INSTALLD, "RemoveExtensionDir failed for param invalid");
1815             return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1816         }
1817         auto ret = RemoveExtensionDir(userId, extensionBundleDir);
1818         if (ret != ERR_OK) {
1819             LOG_E(BMS_TAG_INSTALLD, "remove dir failed: %{public}s", extensionBundleDir.c_str());
1820             return ret;
1821         }
1822     }
1823     return ERR_OK;
1824 }
1825 
RemoveExtensionDir(int32_t userId,const std::string & extensionBundleDir)1826 ErrCode InstalldHostImpl::RemoveExtensionDir(int32_t userId, const std::string &extensionBundleDir)
1827 {
1828     LOG_I(BMS_TAG_INSTALLD, "begin RemoveExtensionDir dir %{public}s", extensionBundleDir.c_str());
1829     for (const auto &el : ServiceConstants::BUNDLE_EL) {
1830         const std::string bundleDataDir = GetBundleDataDir(el, userId);
1831         std::string baseDir = bundleDataDir + ServiceConstants::BASE + extensionBundleDir;
1832         if (!InstalldOperator::DeleteDir(baseDir)) {
1833             LOG_E(BMS_TAG_INSTALLD, "remove base dir %{public}s failed errno:%{public}d", baseDir.c_str(), errno);
1834             return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
1835         }
1836 
1837         std::string databaseDir = bundleDataDir + ServiceConstants::DATABASE + extensionBundleDir;
1838         if (!InstalldOperator::DeleteDir(databaseDir)) {
1839             LOG_E(BMS_TAG_INSTALLD, "remove database dir %{public}s failed errno:%{public}d",
1840                 databaseDir.c_str(), errno);
1841             return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
1842         }
1843 
1844         if (el == ServiceConstants::BUNDLE_EL[1]) {
1845             std::string logDir = bundleDataDir + ServiceConstants::LOG + extensionBundleDir;
1846             if (!InstalldOperator::DeleteDir(logDir)) {
1847                 LOG_E(BMS_TAG_INSTALLD, "remove log dir %{public}s failed errno:%{public}d", logDir.c_str(), errno);
1848                 return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
1849             }
1850         }
1851     }
1852     return ERR_OK;
1853 }
1854 
IsExistExtensionDir(int32_t userId,const std::string & extensionBundleDir,bool & isExist)1855 ErrCode InstalldHostImpl::IsExistExtensionDir(int32_t userId, const std::string &extensionBundleDir, bool &isExist)
1856 {
1857     LOG_I(BMS_TAG_INSTALLD, "IsExistExtensionDir called, userId %{public}d dir %{public}s",
1858         userId, extensionBundleDir.c_str());
1859     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1860         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1861         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1862     }
1863     for (const auto &el : ServiceConstants::BUNDLE_EL) {
1864         const std::string bundleDataDir = GetBundleDataDir(el, userId);
1865         std::string baseDir = bundleDataDir + ServiceConstants::BASE + extensionBundleDir;
1866         if (!InstalldOperator::IsExistDir(baseDir)) {
1867             LOG_I(BMS_TAG_INSTALLD, "dir %{public}s is not existed", baseDir.c_str());
1868             isExist = false;
1869             return ERR_OK;
1870         }
1871 
1872         std::string databaseDir = bundleDataDir + ServiceConstants::DATABASE + extensionBundleDir;
1873         if (!InstalldOperator::IsExistDir(databaseDir)) {
1874             LOG_I(BMS_TAG_INSTALLD, "dir %{public}s is not existed", databaseDir.c_str());
1875             isExist = false;
1876             return ERR_OK;
1877         }
1878 
1879         if (el == ServiceConstants::BUNDLE_EL[1]) {
1880             std::string logDir = bundleDataDir + ServiceConstants::LOG + extensionBundleDir;
1881             if (!InstalldOperator::IsExistDir(logDir)) {
1882                 LOG_I(BMS_TAG_INSTALLD, "dir %{public}s is not existed", logDir.c_str());
1883                 isExist = false;
1884                 return ERR_OK;
1885             }
1886         }
1887     }
1888     isExist = true;
1889     return ERR_OK;
1890 }
1891 
CreateExtensionDataDir(const CreateDirParam & createDirParam)1892 ErrCode InstalldHostImpl::CreateExtensionDataDir(const CreateDirParam &createDirParam)
1893 {
1894     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1895         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1896         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1897     }
1898     if (createDirParam.bundleName.empty() || createDirParam.userId < 0 ||
1899         createDirParam.uid < 0 || createDirParam.gid < 0 || createDirParam.extensionDirs.empty()) {
1900         LOG_E(BMS_TAG_INSTALLD, "Calling the function CreateExtensionDataDir with invalid param");
1901         return ERR_APPEXECFWK_INSTALLD_PARAM_ERROR;
1902     }
1903     LOG_I(BMS_TAG_INSTALLD, "begin to create extension dir for bundle %{public}s, which has %{public}zu extension dir",
1904         createDirParam.bundleName.c_str(), createDirParam.extensionDirs.size());
1905     for (const auto &el : ServiceConstants::BUNDLE_EL) {
1906         if ((createDirParam.createDirFlag == CreateDirFlag::CREATE_DIR_UNLOCKED) &&
1907             (el == ServiceConstants::BUNDLE_EL[0])) {
1908             continue;
1909         }
1910 
1911         std::string bundleDataDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::BASE;
1912         if (access(bundleDataDir.c_str(), F_OK) != 0) {
1913             LOG_W(BMS_TAG_INSTALLD, "Base directory %{public}s does not existed, bundleName:%{public}s",
1914                 bundleDataDir.c_str(), createDirParam.bundleName.c_str());
1915             return ERR_OK;
1916         }
1917         int mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_IRWXO) : S_IRWXU;
1918         if (CreateExtensionDir(createDirParam, bundleDataDir, mode, createDirParam.gid) != ERR_OK) {
1919             LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", bundleDataDir.c_str());
1920             return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
1921         }
1922         AclSetExtensionDirs(createDirParam.debug, bundleDataDir, createDirParam.extensionDirs, true, true);
1923         if (el == ServiceConstants::BUNDLE_EL[1]) {
1924             std::string logParentDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::LOG;
1925             if (CreateExtensionDir(createDirParam, logParentDir, S_IRWXU | S_IRWXG,
1926                 ServiceConstants::LOG_DIR_GID, true) != ERR_OK) {
1927                 LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", logParentDir.c_str());
1928             }
1929         }
1930         mode = createDirParam.debug ? (S_IRWXU | S_IRWXG | S_ISGID | S_IROTH | S_IXOTH) : (S_IRWXU | S_IRWXG | S_ISGID);
1931         std::string databaseParentDir = GetBundleDataDir(el, createDirParam.userId) + ServiceConstants::DATABASE;
1932         if (CreateExtensionDir(createDirParam, databaseParentDir, mode,
1933             ServiceConstants::DATABASE_DIR_GID) != ERR_OK) {
1934             LOG_W(BMS_TAG_INSTALLD, "create extension dir failed, parent dir %{public}s", databaseParentDir.c_str());
1935             return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED;
1936         }
1937         AclSetExtensionDirs(createDirParam.debug, databaseParentDir, createDirParam.extensionDirs, false, true);
1938     }
1939     return ERR_OK;
1940 }
1941 
GetExtensionSandboxTypeList(std::vector<std::string> & typeList)1942 ErrCode InstalldHostImpl::GetExtensionSandboxTypeList(std::vector<std::string> &typeList)
1943 {
1944     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
1945         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
1946         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
1947     }
1948     nlohmann::json jsonBuf;
1949     std::string extensionConfigPath = GetExtensionConfigPath();
1950     if (!ReadFileIntoJson(extensionConfigPath, jsonBuf)) {
1951         LOG_I(BMS_TAG_INSTALLD, "Parse file %{public}s failed", extensionConfigPath.c_str());
1952         return ERR_APPEXECFWK_INSTALL_FAILED_PROFILE_PARSE_FAIL;
1953     }
1954     LoadNeedCreateSandbox(jsonBuf, typeList);
1955     return ERR_OK;
1956 }
1957 
GetExtensionConfigPath() const1958 std::string InstalldHostImpl::GetExtensionConfigPath() const
1959 {
1960 #ifdef CONFIG_POLOCY_ENABLE
1961     char buf[MAX_PATH_LEN] = { 0 };
1962     char *configPath = GetOneCfgFile(EXTENSION_CONFIG_FILE_PATH, buf, MAX_PATH_LEN);
1963     if (configPath == nullptr || configPath[0] == '\0') {
1964         LOG_E(BMS_TAG_INSTALLD, "GetOneCfgFile failed");
1965         return EXTENSION_CONFIG_DEFAULT_PATH;
1966     }
1967     if (strlen(configPath) > MAX_PATH_LEN) {
1968         LOG_E(BMS_TAG_INSTALLD, "configPath length exceeds");
1969         return EXTENSION_CONFIG_DEFAULT_PATH;
1970     }
1971     return configPath;
1972 #else
1973     return EXTENSION_CONFIG_DEFAULT_PATH;
1974 #endif
1975 }
1976 
LoadNeedCreateSandbox(const nlohmann::json & object,std::vector<std::string> & typeList)1977 void InstalldHostImpl::LoadNeedCreateSandbox(const nlohmann::json &object, std::vector<std::string> &typeList)
1978 {
1979     if (!object.contains(EXTENSION_CONFIG_NAME) || !object.at(EXTENSION_CONFIG_NAME).is_array()) {
1980         LOG_E(BMS_TAG_INSTALLD, "Extension config not existed");
1981         return;
1982     }
1983 
1984     for (auto &item : object.at(EXTENSION_CONFIG_NAME).items()) {
1985         const nlohmann::json& jsonObject = item.value();
1986         if (!jsonObject.contains(EXTENSION_TYPE_NAME) || !jsonObject.at(EXTENSION_TYPE_NAME).is_string()) {
1987             continue;
1988         }
1989         std::string extensionType = jsonObject.at(EXTENSION_TYPE_NAME).get<std::string>();
1990         if (LoadExtensionNeedCreateSandbox(jsonObject, extensionType)) {
1991             typeList.emplace_back(extensionType);
1992         }
1993     }
1994 }
1995 
LoadExtensionNeedCreateSandbox(const nlohmann::json & object,std::string extensionTypeName)1996 bool InstalldHostImpl::LoadExtensionNeedCreateSandbox(const nlohmann::json &object, std::string extensionTypeName)
1997 {
1998     if (!object.contains(EXTENSION_SERVICE_NEED_CREATE_SANDBOX) ||
1999         !object.at(EXTENSION_SERVICE_NEED_CREATE_SANDBOX).is_boolean()) {
2000         LOG_E(BMS_TAG_INSTALLD, "need create sandbox config not existed");
2001         return false;
2002     }
2003     return object.at(EXTENSION_SERVICE_NEED_CREATE_SANDBOX).get<bool>();
2004 }
2005 
ReadFileIntoJson(const std::string & filePath,nlohmann::json & jsonBuf)2006 bool InstalldHostImpl::ReadFileIntoJson(const std::string &filePath, nlohmann::json &jsonBuf)
2007 {
2008     if (filePath.length() > PATH_MAX) {
2009         LOG_E(BMS_TAG_INSTALLD, "path length(%{public}u) longer than max length(%{public}d)",
2010             static_cast<unsigned int>(filePath.length()), PATH_MAX);
2011         return false;
2012     }
2013     std::string realPath;
2014     realPath.reserve(PATH_MAX);
2015     realPath.resize(PATH_MAX - 1);
2016     if (realpath(filePath.c_str(), &(realPath[0])) == nullptr) {
2017         LOG_E(BMS_TAG_INSTALLD, "transform real path: %{public}s  error: %{public}d", filePath.c_str(), errno);
2018         return false;
2019     }
2020     if (access(filePath.c_str(), F_OK) != 0) {
2021         LOG_D(BMS_TAG_INSTALLD, "access file %{public}s failed, error: %{public}s", filePath.c_str(), strerror(errno));
2022         return false;
2023     }
2024 
2025     std::fstream in;
2026     char errBuf[256];
2027     errBuf[0] = '\0';
2028     in.open(filePath, std::ios_base::in);
2029     if (!in.is_open()) {
2030         strerror_r(errno, errBuf, sizeof(errBuf));
2031         LOG_E(BMS_TAG_INSTALLD, "the file cannot be open due to  %{public}s, errno:%{public}d", errBuf, errno);
2032         return false;
2033     }
2034 
2035     in.seekg(0, std::ios::end);
2036     int64_t size = in.tellg();
2037     if (size <= 0) {
2038         LOG_E(BMS_TAG_INSTALLD, "the file is an empty file, errno:%{public}d", errno);
2039         in.close();
2040         return false;
2041     }
2042 
2043     in.seekg(0, std::ios::beg);
2044     jsonBuf = nlohmann::json::parse(in, nullptr, false);
2045     in.close();
2046     if (jsonBuf.is_discarded()) {
2047         LOG_E(BMS_TAG_INSTALLD, "bad profile file");
2048         return false;
2049     }
2050 
2051     return true;
2052 }
2053 
InnerRemoveAtomicServiceBundleDataDir(const std::string & bundleName,const int32_t userId,const bool async)2054 ErrCode InstalldHostImpl::InnerRemoveAtomicServiceBundleDataDir(
2055     const std::string &bundleName, const int32_t userId, const bool async)
2056 {
2057     LOG_I(BMS_TAG_INSTALLD, "process atomic service bundleName:%{public}s", bundleName.c_str());
2058     std::vector<std::string> pathName;
2059     if (!InstalldOperator::GetAtomicServiceBundleDataDir(bundleName, userId, pathName)) {
2060         LOG_W(BMS_TAG_INSTALLD, "atomic bundle %{public}s no other path", bundleName.c_str());
2061     }
2062     pathName.emplace_back(bundleName);
2063     LOG_I(BMS_TAG_INSTALLD, "bundle %{public}s need delete path size:%{public}zu", bundleName.c_str(), pathName.size());
2064     ErrCode result = ERR_OK;
2065     for (const auto &name : pathName) {
2066         ErrCode tmpResult = InnerRemoveBundleDataDir(name, userId, async);
2067         if (tmpResult != ERR_OK) {
2068             result = tmpResult;
2069         }
2070     }
2071     return result;
2072 }
2073 
InnerRemoveBundleDataDir(const std::string & bundleName,const int32_t userId,const bool async)2074 ErrCode InstalldHostImpl::InnerRemoveBundleDataDir(
2075     const std::string &bundleName, const int32_t userId, const bool async)
2076 {
2077     for (const auto &el : ServiceConstants::BUNDLE_EL) {
2078         std::string bundleDataDir = GetBundleDataDir(el, userId) + ServiceConstants::BASE + bundleName;
2079         if (!InstalldOperator::DeleteDirFlexible(bundleDataDir, async)) {
2080             LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", bundleDataDir.c_str(), errno);
2081             return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2082         }
2083         std::string databaseDir = GetBundleDataDir(el, userId) + ServiceConstants::DATABASE + bundleName;
2084         if (!InstalldOperator::DeleteDirFlexible(databaseDir, async)) {
2085             LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", databaseDir.c_str(), errno);
2086             return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2087         }
2088         if (el == ServiceConstants::BUNDLE_EL[1]) {
2089             std::string logDir = GetBundleDataDir(el, userId) + ServiceConstants::LOG + bundleName;
2090             if (!InstalldOperator::DeleteDir(logDir)) {
2091                 LOG_E(BMS_TAG_INSTALLD, "remove dir %{public}s failed errno:%{public}d", logDir.c_str(), errno);
2092                 return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2093             }
2094         }
2095     }
2096     if (RemoveShareDir(bundleName, userId) != ERR_OK) {
2097         LOG_E(BMS_TAG_INSTALLD, "failed to remove share dir");
2098         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2099     }
2100     if (RemoveCloudDir(bundleName, userId) != ERR_OK) {
2101         LOG_E(BMS_TAG_INSTALLD, "failed to remove cloud dir");
2102         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2103     }
2104     if (RemoveBackupExtHomeDir(bundleName, userId, DirType::DIR_EL2) != ERR_OK ||
2105         RemoveBackupExtHomeDir(bundleName, userId, DirType::DIR_EL1) != ERR_OK) {
2106         LOG_E(BMS_TAG_INSTALLD, "failed to remove backup ext home dir");
2107         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2108     }
2109     if (RemoveNewBackupExtHomeDir(bundleName, userId, DirType::DIR_EL2) != ERR_OK ||
2110         RemoveNewBackupExtHomeDir(bundleName, userId, DirType::DIR_EL1) != ERR_OK) {
2111         LOG_E(BMS_TAG_INSTALLD, "failed to remove new backup ext home dir");
2112         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2113     }
2114     if (RemoveDistributedDir(bundleName, userId) != ERR_OK) {
2115         LOG_E(BMS_TAG_INSTALLD, "failed to remove distributed file dir");
2116         return ERR_APPEXECFWK_INSTALLD_REMOVE_DIR_FAILED;
2117     }
2118     return ERR_OK;
2119 }
2120 
MoveHapToCodeDir(const std::string & originPath,const std::string & targetPath)2121 ErrCode InstalldHostImpl::MoveHapToCodeDir(const std::string &originPath, const std::string &targetPath)
2122 {
2123     if (!InstalldPermissionMgr::VerifyCallingPermission(Constants::FOUNDATION_UID)) {
2124         LOG_E(BMS_TAG_INSTALLD, "installd permission denied, only used for foundation process");
2125         return ERR_APPEXECFWK_INSTALLD_PERMISSION_DENIED;
2126     }
2127     if (!InstalldOperator::MoveFile(originPath, targetPath)) {
2128         LOG_E(BMS_TAG_INSTALLD, "move file %{public}s to %{public}s failed errno:%{public}d",
2129             originPath.c_str(), targetPath.c_str(), errno);
2130         return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
2131     }
2132     mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
2133     if (!OHOS::ChangeModeFile(targetPath, mode)) {
2134         LOG_E(BMS_TAG_INSTALLD, "change mode failed");
2135         return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
2136     }
2137     if (!InstalldOperator::ChangeFileAttr(targetPath, INSTALLS_UID, INSTALLS_UID)) {
2138         LOG_E(BMS_TAG_INSTALLD, "ChangeAttr %{public}s failed errno:%{public}d", targetPath.c_str(), errno);
2139         return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
2140     }
2141 
2142 #ifdef WITH_SELINUX
2143     const char *context = "u:object_r:data_app_el1_file:s0";
2144     if (lsetfilecon(targetPath.c_str(), context) < 0) {
2145         LOG_E(BMS_TAG_INSTALLD, "setcon %{public}s failed errno:%{public}d", targetPath.c_str(), errno);
2146         return ERR_APPEXECFWK_INSTALLD_MOVE_FILE_FAILED;
2147     }
2148 #endif
2149     return ERR_OK;
2150 }
2151 }  // namespace AppExecFwk
2152 }  // namespace OHOS
2153