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