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 #ifndef FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_INSTALLD_CLIENT_H
17 #define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_INSTALLD_CLIENT_H
18 
19 #include <condition_variable>
20 #include <memory>
21 #include <mutex>
22 #include <shared_mutex>
23 #include <string>
24 
25 #include "nocopyable.h"
26 #include "singleton.h"
27 
28 #include "app_log_wrapper.h"
29 #include "appexecfwk_errors.h"
30 #include "bundle_constants.h"
31 #include "ipc/installd_interface.h"
32 
33 namespace OHOS {
34 namespace AppExecFwk {
35 class InstalldClient : public DelayedSingleton<InstalldClient> {
36 public:
37     /**
38      * @brief Create a bundle code directory through an installd proxy object.
39      * @param bundleDir Indicates the bundle code directory path that to be created.
40      * @return Returns ERR_OK if the bundle directory created successfully; returns error code otherwise.
41      */
42     ErrCode CreateBundleDir(const std::string &bundleDir);
43     /**
44      * @brief Extract the files of a HAP module to the code directory.
45      * @param srcModulePath Indicates the HAP file path.
46      * @param targetPath normal files decompression path.
47      * @param targetSoPath so files decompression path.
48      * @param cpuAbi cpuAbi.
49      * @return Returns ERR_OK if the HAP file extracted successfully; returns error code otherwise.
50      */
51     ErrCode ExtractModuleFiles(const std::string &srcModulePath, const std::string &targetPath,
52         const std::string &targetSoPath, const std::string &cpuAbi);
53     /**
54      * @brief Rename the module directory from temporaily path to the real path.
55      * @param oldPath Indicates the old path name.
56      * @param newPath Indicates the new path name.
57      * @return Returns ERR_OK if the module directory renamed successfully; returns error code otherwise.
58      */
59     ErrCode RenameModuleDir(const std::string &oldPath, const std::string &newPath);
60     /**
61      * @brief Create a bundle data directory.
62      * @param createDirParam Indicates param to be set to the directory.
63      * @return Returns ERR_OK if the bundle data directory created successfully; returns error code otherwise.
64      */
65     ErrCode CreateBundleDataDir(const CreateDirParam &createDirParam);
66 
67     ErrCode CreateBundleDataDirWithVector(const std::vector<CreateDirParam> &createDirParams);
68 
69     /**
70      * @brief Remove a bundle data directory.
71      * @param bundleName Indicates the bundleName data directory path that to be created.
72      * @param userid Indicates userid to be set to the directory.
73      * @return Returns ERR_OK if the bundle data directory created successfully; returns error code otherwise.
74      */
75     ErrCode RemoveBundleDataDir(const std::string &bundleName, const int32_t userId,
76         bool isAtomicService = false, const bool async = false);
77     /**
78      * @brief Remove a module data directory.
79      * @param ModuleDir Indicates the module data directory path that to be created.
80      * @param userid Indicates userid to be set to the directory.
81      * @return Returns ERR_OK if the data directories created successfully; returns error code otherwise.
82      */
83     ErrCode RemoveModuleDataDir(const std::string &ModuleDir, const int userid);
84     /**
85      * @brief Remove a directory.
86      * @param dir Indicates the directory path that to be removed.
87      * @return Returns ERR_OK if the  directory removed successfully; returns error code otherwise.
88      */
89     ErrCode RemoveDir(const std::string &dir);
90     /**
91      * @brief Get disk usage for dir.
92      * @param dir Indicates the directory.
93      * @param isRealPath Indicates isRealPath.
94      * @return Returns true if successfully; returns false otherwise.
95      */
96     int64_t GetDiskUsage(const std::string &dir, bool isRealPath = false);
97     /**
98      * @brief Clean all files in a bundle data directory.
99      * @param bundleDir Indicates the data directory path that to be cleaned.
100      * @return Returns ERR_OK if the data directory cleaned successfully; returns error code otherwise.
101      */
102     ErrCode CleanBundleDataDir(const std::string &bundleDir);
103     /**
104      * @brief Clean a bundle data directory.
105      * @param bundleName Indicates the bundleName data directory path that to be cleaned.
106      * @param userid Indicates userid to be set to the directory.
107      * @param appIndex Indicates app index to be set to the directory.
108      * @return Returns ERR_OK if the bundle data directory cleaned successfully; returns error code otherwise.
109      */
110     ErrCode CleanBundleDataDirByName(const std::string &bundleName, const int userid, const int appIndex = 0);
111     /**
112      * @brief Get bundle Stats.
113      * @param bundleName Indicates the bundle name.
114      * @param userId Indicates the user Id.
115      * @param bundleStats Indicates the bundle Stats.
116      * @return Returns ERR_OK if get stats successfully; returns error code otherwise.
117      */
118     ErrCode GetBundleStats(const std::string &bundleName, const int32_t userId,
119         std::vector<int64_t> &bundleStats, const int32_t uid = Constants::INVALID_UID,
120         const int32_t appIndex = 0, const uint32_t statFlag = 0,
121         const std::vector<std::string> &moduleNameList = {});
122 
123     ErrCode GetAllBundleStats(const int32_t userId,
124         std::vector<int64_t> &bundleStats, const std::vector<int32_t> &uids);
125 
126     /**
127      * @brief Reset the installd proxy object when installd service died.
128      * @return
129      */
130     void ResetInstalldProxy();
131 
132     /**
133      * @brief Set dir apl.
134      * @param dir Indicates the data dir.
135      * @param bundleName Indicates the bundle name.
136      * @param apl Indicates the apl type.
137      * @param isPreInstallApp Indicates the bundle install type.
138      * @param debug Indicates the bundle debug mode.
139      * @return Returns ERR_OK if set apl successfully; returns error code otherwise.
140      */
141     ErrCode SetDirApl(const std::string &dir, const std::string &bundleName, const std::string &apl,
142         bool isPreInstallApp, bool debug);
143 
144     /**
145      * @brief Get all cache file path.
146      * @param dir Indicates the data dir.
147      * @param cachesPath Indicates the cache file path.
148      * @return Returns ERR_OK if get cache file path successfully; returns error code otherwise.
149      */
150     ErrCode GetBundleCachePath(const std::string &dir, std::vector<std::string> &cachePath);
151 
152     ErrCode ScanDir(
153         const std::string &dir, ScanMode scanMode, ResultMode resultMode, std::vector<std::string> &paths);
154 
155     ErrCode MoveFile(const std::string &oldPath, const std::string &newPath);
156 
157     ErrCode CopyFile(const std::string &oldPath, const std::string &newPath,
158         const std::string &signatureFilePath = "");
159 
160     ErrCode Mkdir(
161         const std::string &dir, const int32_t mode, const int32_t uid, const int32_t gid);
162 
163     ErrCode GetFileStat(const std::string &file, FileStat &fileStat);
164 
165     ErrCode ExtractDiffFiles(const std::string &filePath, const std::string &targetPath,
166         const std::string &cpuAbi);
167 
168     ErrCode ApplyDiffPatch(const std::string &oldSoPath, const std::string &diffFilePath,
169         const std::string &newSoPath, int32_t uid = Constants::INVALID_UID);
170 
171     ErrCode IsExistDir(const std::string &dir, bool &isExist);
172 
173     ErrCode IsExistFile(const std::string &path, bool &isExist);
174 
175     ErrCode IsExistApFile(const std::string &path, bool &isExist);
176 
177     ErrCode IsDirEmpty(const std::string &dir, bool &isDirEmpty);
178 
179     ErrCode ObtainQuickFixFileDir(const std::string &dir, std::vector<std::string> &dirVec);
180 
181     ErrCode CopyFiles(const std::string &sourceDir, const std::string &destinationDir);
182 
183     ErrCode ExtractFiles(const ExtractParam &extractParam);
184 
185     ErrCode ExtractHnpFiles(const std::string &hnpPackageInfo, const ExtractParam &extractParam);
186 
187     ErrCode ProcessBundleInstallNative(const std::string &userId, const std::string &hnpRootPath,
188         const std::string &hapPath, const std::string &cpuAbi, const std::string &packageName);
189 
190     ErrCode ProcessBundleUnInstallNative(const std::string &userId, const std::string &bundleName);
191 
192     ErrCode GetNativeLibraryFileNames(const std::string &filePath, const std::string &cpuAbi,
193         std::vector<std::string> &fileNames);
194 
195     ErrCode ExecuteAOT(const AOTArgs &aotArgs, std::vector<uint8_t> &pendSignData);
196 
197     ErrCode PendSignAOT(const std::string &anFileName, const std::vector<uint8_t> &signData);
198 
199     ErrCode StopAOT();
200 
201     ErrCode DeleteUninstallTmpDirs(const std::vector<std::string> &dirs);
202 
203     ErrCode VerifyCodeSignature(const CodeSignatureParam &codeSignatureParam);
204 
205     ErrCode VerifyCodeSignatureForHap(const CodeSignatureParam &codeSignatureParam);
206 
207     ErrCode CheckEncryption(const CheckEncryptionParam &checkEncryptionParam, bool &isEncryption);
208 
209     ErrCode MoveFiles(const std::string &srcDir, const std::string &desDir);
210 
211     ErrCode ExtractDriverSoFiles(const std::string &srcPath,
212         const std::unordered_multimap<std::string, std::string> &dirMap);
213 
214     void OnLoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject);
215 
216     void OnLoadSystemAbilityFail();
217 
218     bool StartInstalldService();
219 
220     ErrCode ExtractEncryptedSoFiles(const std::string &hapPath, const std::string &realSoFilesPath,
221         const std::string &cpuAbi, const std::string &tmpSoPath, int32_t uid);
222 
223     ErrCode DeliverySignProfile(const std::string &bundleName, int32_t profileBlockLength,
224         const unsigned char *profileBlock);
225 
226     ErrCode RemoveSignProfile(const std::string &bundleName);
227 
228     ErrCode SetEncryptionPolicy(int32_t uid, const std::string &bundleName,
229         const int32_t userId, std::string &keyId);
230 
231     ErrCode DeleteEncryptionKeyId(const std::string &bundleName, const int32_t userId);
232 
233     ErrCode RemoveExtensionDir(int32_t userId, const std::vector<std::string> &extensionBundleDirs);
234 
235     ErrCode IsExistExtensionDir(int32_t userId, const std::string &extensionBundleDir, bool &isExist);
236 
237     ErrCode CreateExtensionDataDir(const CreateDirParam &createDirParam);
238 
239     ErrCode GetExtensionSandboxTypeList(std::vector<std::string> &typeList);
240 
241     ErrCode MoveHapToCodeDir(const std::string &originPath, const std::string &targetPath);
242 
243 private:
244     sptr<IInstalld> GetInstalldProxy();
245     bool LoadInstalldService();
246 
247     template<typename F, typename... Args>
CallService(F func,Args &&...args)248     ErrCode CallService(F func, Args&&... args)
249     {
250         int32_t maxRetryTimes = 2;
251         ErrCode errCode = ERR_APPEXECFWK_INSTALLD_SERVICE_DIED;
252         for (int32_t retryTimes = 0; retryTimes < maxRetryTimes; retryTimes++) {
253             auto proxy = GetInstalldProxy();
254             if (proxy == nullptr) {
255                 return ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR;
256             }
257             errCode = (proxy->*func)(std::forward<Args>(args)...);
258             if (errCode == ERR_APPEXECFWK_INSTALLD_SERVICE_DIED) {
259                 APP_LOGE("CallService failed, retry times: %{public}d", retryTimes + 1);
260                 ResetInstalldProxy();
261             } else {
262                 return errCode;
263             }
264         }
265         return errCode;
266     }
267 
268 private:
269     bool loadSaFinished_;
270     std::mutex mutex_;
271     std::mutex loadSaMutex_;
272     std::mutex getProxyMutex_;
273     std::condition_variable loadSaCondition_;
274     sptr<IInstalld> installdProxy_;
275     sptr<IRemoteObject::DeathRecipient> recipient_;
276 };
277 }  // namespace AppExecFwk
278 }  // namespace OHOS
279 #endif  // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_INSTALLD_CLIENT_H