• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 #include "bundle_test_tool.h"
16 
17 #include <chrono>
18 #include <cstdlib>
19 #include <cstring>
20 #include <future>
21 #include <getopt.h>
22 #include <iostream>
23 #include <set>
24 #include <sstream>
25 #include <thread>
26 #include <unistd.h>
27 #include <vector>
28 
29 #include "accesstoken_kit.h"
30 #include "app_log_wrapper.h"
31 #include "appexecfwk_errors.h"
32 #include "bundle_command_common.h"
33 #include "bundle_death_recipient.h"
34 #include "bundle_dir.h"
35 #include "bundle_mgr_client.h"
36 #include "bundle_mgr_proxy.h"
37 #include "bundle_tool_callback_stub.h"
38 #include "common_event_manager.h"
39 #include "common_event_support.h"
40 #include "permission_define.h"
41 #include "iservice_registry.h"
42 #include "data_group_info.h"
43 #include "directory_ex.h"
44 #include "parameter.h"
45 #include "parameters.h"
46 #include "process_cache_callback_host.h"
47 #include "nativetoken_kit.h"
48 #include "token_setproc.h"
49 #include "system_ability_definition.h"
50 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
51 #include "quick_fix_status_callback_host_impl.h"
52 #endif
53 #include "status_receiver_impl.h"
54 #include "string_ex.h"
55 #include "json_util.h"
56 
57 namespace OHOS {
58 namespace AppExecFwk {
59 namespace {
60 using OptionHandler = std::function<void(const std::string&)>;
61 
62 const std::string LINE_BREAK = "\n";
63 constexpr int32_t SLEEP_SECONDS = 20;
64 // param
65 const int32_t INDEX_OFFSET = 2;
66 // quick fix error code
67 const int32_t ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED = 801;
68 const int32_t INITIAL_SANDBOX_APP_INDEX = 1000;
69 const int32_t CODE_PROTECT_UID = 7666;
70 const int32_t MAX_WAITING_TIME = 600;
71 const int32_t MAX_PARAMS_FOR_UNINSTALL = 4;
72 // system param
73 constexpr const char* IS_ENTERPRISE_DEVICE = "const.edm.is_enterprise_device";
74 // quick fix error message
75 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR = "error: quick fix internal error.\n";
76 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR = "error: param error.\n";
77 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED = "error: profile parse failed.\n";
78 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME = "error: not same bundle name.\n";
79 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME = "error: not same version code.\n";
80 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME = "error: not same version name.\n";
81 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME =
82     "error: not same patch version code.\n";
83 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME =
84     "error: not same patch version name.\n";
85 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME = "error: not same patch type.\n";
86 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE = "error: unknown quick fix type.\n";
87 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE = "error: patch so incompatible.\n";
88 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME = "error: same moduleName.\n";
89 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST = "error: bundle name is not existed.\n";
90 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST = "error: module name is not existed.\n";
91 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME = "error: signature is not existed.\n";
92 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED = "error: quick fix add hqf failed.\n";
93 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED =
94     "error: quick fix save innerAppQuickFix failed.\n";
95 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR =
96     "error: quick fix version code require greater than original hqf.\n";
97 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE = "error: no this quick fix info in database.\n";
98 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS = "error: wrong quick fix status.\n";
99 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO =
100     "error: cannot obtain the bundleInfo from data mgr.\n";
101 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED = "error: quick fix remove path failed.\n";
102 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED = "error: extract diff files failed.\n";
103 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED = "error: apply diff patch failed.\n";
104 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN = "error: unknown.\n";
105 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED = "feature is not supported.\n";
106 const std::string MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT = "error: quick fix operation time out.\n";
107 const std::string MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED = "error: bundleMgr service is dead.\n";
108 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE =
109     "error: hotreload not support release bundle.\n";
110 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED = "error: patch type already existed.\n";
111 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED =
112     "error: hotreload type already existed.\n";
113 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO =
114     "error: no patch info in bundleInfo.\n";
115 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED = "error: quick fix move hqf file failed.\n";
116 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED = "error: quick fix create path failed.\n";
117 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB =
118     "error: old patch or hot reload in db.\n";
119 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SEND_REQUEST_FAILED = "error: send request failed.\n";
120 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REAL_PATH_FAILED = "error: obtain realpath failed.\n";
121 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATH = "error: input invalid path.\n";
122 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OPEN_SOURCE_FILE_FAILED = "error: open source file failed.\n";
123 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_FD_FAILED = "error: create file descriptor failed.\n";
124 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_TARGET_DIR = "error: invalid designated target dir\n";
125 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_TARGET_DIR_FAILED = "error: create target dir failed.\n";
126 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PERMISSION_DENIED = "error: quick fix permission denied.\n";
127 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_WRITE_FILE_FAILED = "error: write file to target dir failed.\n";
128 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED =
129     "error: the hqf of release hap cannot contains resources/rawfile.\n";
130 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM =
131     "error: invalid param for setting debug mode.\n";
132 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR =
133     "error: internal error for setting debug mode.\n";
134 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR = "error: parcel error for setting debug mode.\n";
135 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR = "error: send request error.\n";
136 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED = "error: uid check failed.\n";
137 
138 static const std::string TOOL_NAME = "bundle_test_tool";
139 static const std::string HELP_MSG =
140     "usage: bundle_test_tool <command> <options>\n"
141     "These are common bundle_test_tool commands list:\n"
142     "  help                             list available commands\n"
143     "  setrm                            set module isRemovable by given bundle name and module name\n"
144     "  getrm                            obtain the value of isRemovable by given bundle name and module name\n"
145     "  installSandbox                   indicates install sandbox\n"
146     "  uninstallSandbox                 indicates uninstall sandbox\n"
147     "  uninstallPreInstallBundle        indicates uninstall preinstall bundle\n"
148     "  dumpSandbox                      indicates dump sandbox info\n"
149     "  getStr                           obtain the value of label by given bundle name, module name and label id\n"
150     "  getIcon                          obtain the value of icon by given bundle name, module name, "
151     "density and icon id\n"
152     "  addAppInstallRule                obtain the value of install controlRule by given some app id "
153     "control rule type, user id and euid\n"
154     "  getAppInstallRule                obtain the value of install controlRule by given some app id "
155     "rule type, user id and euid\n"
156     "  deleteAppInstallRule             obtain the value of install controlRule by given some app id "
157     "user id and euid\n"
158     "  cleanAppInstallRule              obtain the value of install controlRule by given rule type "
159     "user id and euid\n"
160     "  addAppRunningRule                obtain the value of app running control rule "
161     "by given controlRule user id and euidn\n"
162     "  deleteAppRunningRule             obtain the value of app running control rule "
163     "by given controlRule user id and euid\n"
164     "  cleanAppRunningRule              obtain the value of app running control "
165     "rule by given user id and euid\n"
166     "  getAppRunningControlRule         obtain the value of app running control rule "
167     "by given user id and euid and some app id\n"
168     "  getAppRunningControlRuleResult   obtain the value of app running control rule "
169     "by given bundleName user id, euid and controlRuleResult\n"
170     "  deployQuickFix                   deploy a quick fix patch of an already installed bundle\n"
171     "  switchQuickFix                   switch a quick fix patch of an already installed bundle\n"
172     "  deleteQuickFix                   delete a quick fix patch of an already installed bundle\n"
173     "  setDebugMode                     enable signature debug mode\n"
174     "  getBundleStats                   get bundle stats\n"
175     "  getAppProvisionInfo              get appProvisionInfo\n"
176     "  getDistributedBundleName         get distributedBundleName\n"
177     "  eventCB                          register then unregister bundle event callback\n"
178     "  resetAOTCompileStatus            reset AOTCompileStatus\n"
179     "  sendCommonEvent                  send common event\n"
180     "  queryDataGroupInfos              obtain the data group infos of the application\n"
181     "  getGroupDir                      obtain the data group dir path by data group id\n"
182     "  getJsonProfile                   obtain the json string of the specified module\n"
183     "  getOdid                          obtain the odid of the application\n"
184     "  getUidByBundleName               obtain the uid string of the specified bundle\n"
185     "  implicitQuerySkillUriInfo        obtain the skill uri info of the implicit query ability\n"
186     "  queryAbilityInfoByContinueType   get ability info by continue type\n"
187     "  cleanBundleCacheFilesAutomatic   clear cache data of a specified size\n"
188     "  getContinueBundleName            get continue bundle name list\n"
189     "  updateAppEncryptedStatus         update app encrypted status\n"
190     "  getDirByBundleNameAndAppIndex    obtain the dir by bundleName and appIndex\n"
191     "  getAllBundleDirs                 obtain all bundle dirs \n"
192     "  getAllBundleCacheStat            obtain all bundle cache size \n"
193     "  cleanAllBundleCache              clean all bundle cache \n"
194     "  isBundleInstalled                determine whether the bundle is installed based on bundleName user "
195     "and appIndex\n"
196     "  getCompatibleDeviceType          obtain the compatible device type based on bundleName\n"
197     "  getSimpleAppInfoForUid           get bundlename list and appIndex list by uid list\n"
198     "  getBundleNameByAppId             get bundlename by appid or appIdentifier\n"
199     "  getAssetAccessGroups             get asset access groups by bundlename\n"
200     "  setAppDistributionTypes          set white list of appDistributionType\n";
201 
202 
203 const std::string HELP_MSG_GET_REMOVABLE =
204     "usage: bundle_test_tool getrm <options>\n"
205     "eg:bundle_test_tool getrm -m <module-name> -n <bundle-name> \n"
206     "options list:\n"
207     "  -h, --help                             list available commands\n"
208     "  -n, --bundle-name  <bundle-name>       get isRemovable by moduleNmae and bundleName\n"
209     "  -m, --module-name <module-name>        get isRemovable by moduleNmae and bundleName\n";
210 
211 const std::string HELP_MSG_NO_REMOVABLE_OPTION =
212     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
213     "and a module name with '-m' or '--module-name' \n";
214 
215 const std::string HELP_MSG_SET =
216     "usage: bundle_test_tool setrm <options>\n"
217     "eg:bundle_test_tool setrm -m <module-name> -n <bundle-name> -i 1\n"
218     "options list:\n"
219     "  -h, --help                               list available commands\n"
220     "  -n, --bundle-name  <bundle-name>         set isRemovable by moduleNmae and bundleName\n"
221     "  -i, --is-removable <is-removable>        set isRemovable  0 or 1\n"
222     "  -m, --module-name <module-name>          set isRemovable by moduleNmae and bundleName\n";
223 
224 const std::string HELP_MSG_INSTALL_SANDBOX =
225     "usage: bundle_test_tool installSandbox <options>\n"
226     "options list:\n"
227     "  -h, --help                             list available commands\n"
228     "  -u, --user-id <user-id>                specify a user id\n"
229     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n"
230     "  -d, --dlp-type <dlp-type>              specify type of the sandbox application\n";
231 
232 const std::string HELP_MSG_UNINSTALL_SANDBOX =
233     "usage: bundle_test_tool uninstallSandbox <options>\n"
234     "options list:\n"
235     "  -h, --help                             list available commands\n"
236     "  -u, --user-id <user-id>                specify a user id\n"
237     "  -a, --app-index <app-index>            specify a app index\n"
238     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
239 
240 const std::string HELP_MSG_DUMP_SANDBOX =
241     "usage: bundle_test_tool dumpSandbox <options>\n"
242     "options list:\n"
243     "  -h, --help                             list available commands\n"
244     "  -u, --user-id <user-id>                specify a user id\n"
245     "  -a, --app-index <app-index>            specify a app index\n"
246     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
247 
248 const std::string HELP_MSG_GET_STRING =
249     "usage: bundle_test_tool getStr <options>\n"
250     "eg:bundle_test_tool getStr -m <module-name> -n <bundle-name> -u <user-id> -i --id <id> \n"
251     "options list:\n"
252     "  -h, --help                             list available commands\n"
253     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
254     "  -m, --module-name <module-name>        specify module name of the application\n"
255     "  -u, --user-id <user-id>                specify a user id\n"
256     "  -i, --id <id>                          specify a label id of the application\n";
257 
258 const std::string HELP_MSG_GET_ICON =
259     "usage: bundle_test_tool getIcon <options>\n"
260     "eg:bundle_test_tool getIcon -m <module-name> -n <bundle-name> -u <user-id> -d --density <density> -i --id <id> \n"
261     "options list:\n"
262     "  -h, --help                             list available commands\n"
263     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
264     "  -m, --module-name <module-name>        specify module name of the application\n"
265     "  -u, --user-id <user-id>                specify a user id\n"
266     "  -d, --density <density>                specify a density\n"
267     "  -i, --id <id>                          specify a icon id of the application\n";
268 
269 const std::string HELP_MSG_NO_GETSTRING_OPTION =
270     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
271     "and a module name with '-m' or '--module-name' \n"
272     "and a userid with '-u' or '--user-id' \n"
273     "and a labelid with '-i' or '--id' \n";
274 
275 const std::string HELP_MSG_NO_GETICON_OPTION =
276     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
277     "and a module name with '-m' or '--module-name' \n"
278     "and a userid with '-u' or '--user-id' \n"
279     "and a density with '-d' or '--density' \n"
280     "and a iconid with '-i' or '--id' \n";
281 
282 const std::string HELP_MSG_ADD_INSTALL_RULE =
283     "usage: bundle_test_tool <options>\n"
284     "eg:bundle_test_tool addAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
285     "options list:\n"
286     "  -h, --help                             list available commands\n"
287     "  -a, --app-id <app-id>                  specify app id of the application\n"
288     "  -e, --euid <eu-id>                     default euid value is 3057\n"
289     "  -t, --control-rule-type                specify control type of the application\n"
290     "  -u, --user-id <user-id>                specify a user id\n";
291 
292 const std::string HELP_MSG_GET_INSTALL_RULE =
293     "usage: bundle_test_tool <options>\n"
294     "eg:bundle_test_tool getAppInstallRule -t <control-rule-type> -u <user-id> \n"
295     "options list:\n"
296     "  -h, --help                             list available commands\n"
297     "  -e, --euid <eu-id>                     default euid value is 3057\n"
298     "  -t, --control-rule-type                specify control type of the application\n"
299     "  -u, --user-id <user-id>                specify a user id\n";
300 
301 const std::string HELP_MSG_DELETE_INSTALL_RULE =
302     "usage: bundle_test_tool <options>\n"
303     "eg:bundle_test_tool deleteAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
304     "options list:\n"
305     "  -h, --help                             list available commands\n"
306     "  -e, --euid <eu-id>                     default euid value is 3057\n"
307     "  -a, --app-id <app-id>                  specify app id of the application\n"
308     "  -t, --control-rule-type                specify control type of the application\n"
309     "  -u, --user-id <user-id>                specify a user id\n";
310 
311 const std::string HELP_MSG_CLEAN_INSTALL_RULE =
312     "usage: bundle_test_tool <options>\n"
313     "eg:bundle_test_tool cleanAppInstallRule -t <control-rule-type> -u <user-id> \n"
314     "options list:\n"
315     "  -h, --help                             list available commands\n"
316     "  -e, --euid <eu-id>                     default euid value is 3057\n"
317     "  -t, --control-rule-type                specify control type of the application\n"
318     "  -u, --user-id <user-id>                specify a user id\n";
319 
320 const std::string HELP_MSG_ADD_APP_RUNNING_RULE =
321     "usage: bundle_test_tool <options>\n"
322     "eg:bundle_test_tool addAppRunningRule -c <control-rule> -u <user-id> \n"
323     "options list:\n"
324     "  -h, --help                             list available commands\n"
325     "  -e, --euid <eu-id>                     default euid value is 3057\n"
326     "  -c, --control-rule                     specify control rule of the application\n"
327     "  -u, --user-id <user-id>                specify a user id\n";
328 
329 const std::string HELP_MSG_DELETE_APP_RUNNING_RULE =
330     "usage: bundle_test_tool <options>\n"
331     "eg:bundle_test_tool deleteAppRunningRule -c <control-rule> -u <user-id> \n"
332     "options list:\n"
333     "  -h, --help                             list available commands\n"
334     "  -e, --euid <eu-id>                     default euid value is 3057\n"
335     "  -c, --control-rule                     specify control rule of the application\n"
336     "  -u, --user-id <user-id>                specify a user id\n";
337 
338 const std::string HELP_MSG_CLEAN_APP_RUNNING_RULE =
339     "usage: bundle_test_tool <options>\n"
340     "eg:bundle_test_tool cleanAppRunningRule -u <user-id> \n"
341     "options list:\n"
342     "  -h, --help                             list available commands\n"
343     "  -e, --euid <eu-id>                     default euid value is 3057\n"
344     "  -u, --user-id <user-id>                specify a user id\n";
345 
346 const std::string HELP_MSG_GET_APP_RUNNING_RULE =
347     "usage: bundle_test_tool <options>\n"
348     "eg:bundle_test_tool getAppRunningControlRule -u <user-id> \n"
349     "options list:\n"
350     "  -h, --help                             list available commands\n"
351     "  -e, --euid <eu-id>                     default euid value is 3057\n"
352     "  -u, --user-id <user-id>                specify a user id\n";
353 
354 const std::string HELP_MSG_GET_APP_RUNNING_RESULT_RULE =
355     "usage: bundle_test_tool <options>\n"
356     "eg:bundle_test_tool getAppRunningControlRuleResult -n <bundle-name> \n"
357     "options list:\n"
358     "  -h, --help                             list available commands\n"
359     "  -e, --euid <eu-id>                     default euid value is 3057\n"
360     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
361     "  -u, --user-id <user-id>                specify a user id\n";
362 
363 const std::string HELP_MSG_AUTO_CLEAN_CACHE_RULE =
364     "usage: bundle_test_tool <options>\n"
365     "eg:bundle_test_tool cleanBundleCacheFilesAutomatic -s <cache-size> \n"
366     "options list:\n"
367     "  -h, --help                             list available commands\n"
368     "  -s, --cache-size <cache-size>          specify the cache size that needs to be cleaned\n";
369 
370 const std::string HELP_MSG_NO_ADD_INSTALL_RULE_OPTION =
371     "error: you must specify a app id with '-a' or '--app-id' \n"
372     "and a control type with '-t' or '--control-rule-type' \n"
373     "and a userid with '-u' or '--user-id' \n";
374 
375 const std::string HELP_MSG_NO_GET_INSTALL_RULE_OPTION =
376     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
377     "and a userid with '-u' or '--user-id' \n";
378 
379 const std::string HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION =
380     "error: you must specify a control type with '-a' or '--app-id' \n"
381     "and a userid with '-u' or '--user-id' \n";
382 
383 const std::string HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION =
384     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
385     "and a userid with '-u' or '--user-id' \n";
386 
387 const std::string HELP_MSG_NO_APP_RUNNING_RULE_OPTION =
388     "error: you must specify a app running type with '-c' or '--control-rule' \n"
389     "and a userid with '-u' or '--user-id' \n";
390 
391 const std::string HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION =
392     "error: you must specify a app running type with a userid '-u' or '--user-id \n";
393 
394 const std::string HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION =
395     "error: you must specify a app running type with '-a' or '--app-id' \n"
396     "and a userid with '-u' or '--user-id' \n";
397 
398 const std::string HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION =
399     "error: you must specify a app running type with '-n' or '--bundle-name' \n"
400     "and a userid with '-u' or '--user-id' \n";
401 
402 const std::string HELP_MSG_NO_AUTO_CLEAN_CACHE_OPTION =
403     "error: you must specify a cache size with '-s' or '--cache-size' \n";
404 
405 const std::string HELP_MSG_DEPLOY_QUICK_FIX =
406     "usage: bundle_test_tool deploy quick fix <options>\n"
407     "eg:bundle_test_tool deployQuickFix -p <quickFixPath> \n"
408     "options list:\n"
409     "  -h, --help                             list available commands\n"
410     "  -p, --patch-path  <patch-path>         specify patch path of the patch\n"
411     "  -d, --debug  <debug>                   specify deploy mode, 0 represents release, 1 represents debug\n";
412 
413 const std::string HELP_MSG_SWITCH_QUICK_FIX =
414     "usage: bundle_test_tool switch quick fix <options>\n"
415     "eg:bundle_test_tool switchQuickFix -n <bundle-name> \n"
416     "options list:\n"
417     "  -h, --help                             list available commands\n"
418     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n"
419     "  -e, --enbale  <enable>                 enable a deployed patch of disable an under using patch,\n"
420     "                                         1 represents enable and 0 represents disable\n";
421 
422 const std::string HELP_MSG_DELETE_QUICK_FIX =
423     "usage: bundle_test_tool delete quick fix <options>\n"
424     "eg:bundle_test_tool deleteQuickFix -n <bundle-name> \n"
425     "options list:\n"
426     "  -h, --help                             list available commands\n"
427     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n";
428 
429 const std::string HELP_MSG_SET_DEBUG_MODE =
430     "usage: bundle_test_tool setDebugMode <options>\n"
431     "eg:bundle_test_tool setDebugMode -e <0/1>\n"
432     "options list:\n"
433     "  -h, --help                             list available commands\n"
434     "  -e, --enable  <enable>                 enable signature debug mode, 1 represents enable debug mode and 0\n"
435     "                                         represents disable debug mode\n";
436 
437 const std::string HELP_MSG_GET_BUNDLE_STATS =
438     "usage: bundle_test_tool getBundleStats <options>\n"
439     "eg:bundle_test_tool getBundleStats -n <bundle-name>\n"
440     "options list:\n"
441     "  -h, --help                             list available commands\n"
442     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
443     "  -u, --user-id <user-id>                specify a user id\n"
444     "  -a, --app-index <app-index>            specify a app index\n";
445 
446 
447 const std::string HELP_MSG_GET_APP_PROVISION_INFO =
448     "usage: bundle_test_tool getAppProvisionInfo <options>\n"
449     "eg:bundle_test_tool getAppProvisionInfo -n <bundle-name>\n"
450     "options list:\n"
451     "  -h, --help                             list available commands\n"
452     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
453     "  -u, --user-id <user-id>                specify a user id\n";
454 
455 const std::string HELP_MSG_GET_DISTRIBUTED_BUNDLE_NAME =
456     "usage: bundle_test_tool getDistributedBundleName <options>\n"
457     "eg:bundle_test_tool getDistributedBundleName -n <network-id> -a <access-token-id>\n"
458     "options list:\n"
459     "  -h, --help                                   list available commands\n"
460     "  -n, --network-id  <network-id>               specify networkId of the application\n"
461     "  -a, --access-token-id <access-token-id>      specify a accessTokenId of the application \n";
462 
463 const std::string HELP_MSG_BUNDLE_EVENT_CALLBACK =
464     "usage: bundle_test_tool eventCB <options>\n"
465     "options list:\n"
466     "  -h, --help           list available commands\n"
467     "  -o, --onlyUnregister only call unregister, default will call register then unregister\n"
468     "  -u, --uid            specify a uid, default is foundation uid\n";
469 
470 const std::string HELP_MSG_RESET_AOT_COMPILE_StATUS =
471     "usage: bundle_test_tool resetAOTCompileStatus <options>\n"
472     "options list:\n"
473     "  -h, --help           list available commands\n"
474     "  -b, --bundle-name    specify bundle name\n"
475     "  -m, --module-name    specify module name\n"
476     "  -t, --trigger-mode   specify trigger mode, default is 0\n"
477     "  -u, --uid            specify a uid, default is bundleName's uid\n";
478 
479 const std::string HELP_MSG_GET_PROXY_DATA =
480     "usage: bundle_test_tool getProxyDataInfos <options>\n"
481     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -u <user-id>\n"
482     "options list:\n"
483     "  -h, --help                             list available commands\n"
484     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
485     "  -m, --module-name <module-name>        specify module name of the application\n"
486     "  -u, --user-id <user-id>                specify a user id\n";
487 
488 const std::string HELP_MSG_GET_ALL_PROXY_DATA =
489     "usage: bundle_test_tool getAllProxyDataInfos <options>\n"
490     "eg:bundle_test_tool getProxyDataInfos -u <user-id>\n"
491     "options list:\n"
492     "  -h, --help                             list available commands\n"
493     "  -u, --user-id <user-id>                specify a user id\n";
494 
495 const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION =
496     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
497 
498 const std::string HELP_MSG_NO_NETWORK_ID_OPTION =
499     "error: you must specify a network id with '-n' or '--network-id' \n";
500 
501 const std::string HELP_MSG_NO_ACCESS_TOKEN_ID_OPTION =
502     "error: you must specify a access token id with '-n' or '--access-token-id' \n";
503 
504 const std::string HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE =
505     "usage: bundle_test_tool setExtNameOrMimeTypeToApp <options>\n"
506     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -a <ability-name>\n"
507     "options list:\n"
508     "  -h, --help                             list available commands\n"
509     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
510     "  -m, --module-name <module-name>        specify module name of the application\n"
511     "  -a, --ability-name <ability-name>      specify ability name of the application\n"
512     "  -e, --ext-name <ext-name>              specify the ext-name\n"
513     "  -t, --mime-type <mime-type>            specify the mime-type\n";
514 
515 const std::string HELP_MSG_DEL_EXT_NAME_OR_MIME_TYPE =
516     "usage: bundle_test_tool setExtNameOrMimeTypeToApp <options>\n"
517     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -a <ability-name>\n"
518     "options list:\n"
519     "  -h, --help                             list available commands\n"
520     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
521     "  -m, --module-name <module-name>        specify module name of the application\n"
522     "  -a, --ability-name <ability-name>      specify ability name of the application\n"
523     "  -e, --ext-name <ext-name>              specify the ext-name\n"
524     "  -t, --mime-type <mime-type>            specify the mime-type\n";
525 
526 const std::string HELP_MSG_QUERY_DATA_GROUP_INFOS =
527     "usage: bundle_test_tool queryDataGroupInfos <options>\n"
528     "eg:bundle_test_tool queryDataGroupInfos -n <bundle-name> -u <user-id>\n"
529     "options list:\n"
530     "  -h, --help                             list available commands\n"
531     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
532     "  -u, --user-id <user-id>                specify a user id\n";
533 
534 const std::string HELP_MSG_GET_GROUP_DIR =
535     "usage: bundle_test_tool getGroupDir <options>\n"
536     "eg:bundle_test_tool getGroupDir -d <data-group-id>\n"
537     "options list:\n"
538     "  -h, --help                             list available commands\n"
539     "  -d, --data-group-id  <data-group-id>       specify bundle name of the application\n";
540 
541 const std::string HELP_MSG_NO_GET_UID_BY_BUNDLENAME =
542     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
543     "and a userId with '-u' or '--user-id' \n"
544     "and a appIndex with '-a' or '--app-index' \n";
545 
546 const std::string HELP_MSG_GET_DIR_BY_BUNDLENAME_AND_APP_INDEX =
547     "usage: bundle_test_tool getDirByBundleNameAndAppIndex <options>\n"
548     "eg:bundle_test_tool getDirByBundleNameAndAppIndex -n <bundle-name> -a <app-index>\n"
549     "options list:\n"
550     "  -h, --help                             list available commands\n"
551     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
552     "  -a, --app-index <app-index>            specify a app index\n";
553 
554 const std::string HELP_MSG_GET_ALL_BUNDLE_DIRS =
555     "usage: bundle_test_tool getAllBundleDirs <options>\n"
556     "eg:bundle_test_tool getAllBundleDirs -u <user-id>\n"
557     "options list:\n"
558     "  -h, --help                             list available commands\n"
559     "  -u, --user-id <user-id>                specify a user id\n";
560 
561 const std::string HELP_MSG_GET_ALL_BUNDLE_CACHE_STAT =
562     "usage: bundle_test_tool getAllBundleCacheStat <options>\n"
563     "eg:bundle_test_tool getAllBundleCacheStat\n"
564     "options list:\n"
565     "  -h, --help                             list available commands\n"
566     "  -u, --uid <uid>                specify a uid\n";
567 
568 const std::string HELP_MSG_CLEAN_ALL_BUNDLE_CACHE =
569     "usage: bundle_test_tool cleanAllBundleCache <options>\n"
570     "eg:bundle_test_tool cleanAllBundleCache\n"
571     "options list:\n"
572     "  -h, --help                     list available commands\n"
573     "  -u, --uid <uid>                specify a uid\n";
574 
575 const std::string HELP_MSG_UPDATE_APP_EXCRYPTED_STATUS =
576     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
577     "and a isExisted with '-e' or '--existed' \n"
578     "and a appIndex with '-a' or '--app-index' \n";
579 
580 const std::string HELP_MSG_NO_GET_JSON_PROFILE_OPTION =
581     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
582     "and a module name with '-m' or '--module-name' \n"
583     "and a userId with '-u' or '--user-id' \n"
584     "and a json profile type with '-p' or '--profile-type' \n";
585 
586 const std::string HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION =
587     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
588 
589 const std::string HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO =
590     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
591     "and a action with '-a' or '--action' \n"
592     "and a entity with '-e' or '--entity' \n";
593 
594 const std::string HELP_MSG_GET_ODID =
595     "usage: bundle_test_tool getOdid <options>\n"
596     "eg:bundle_test_tool getOdid -u <uid>\n"
597     "options list:\n"
598     "  -h, --help               list available commands\n"
599     "  -u, --uid  <uid>         specify uid of the application\n";
600 
601 const std::string HELP_MSG_GET_COMPATIBLE_DEVICE_TYPE =
602     "usage: bundle_test_tool getCompatibleDeviceType <option>\n"
603     "eg: bundle_test_tool getCompatibleDeviceType -n <bundle-name>\n"
604     "options list:\n"
605     "  -h, --help                             list available commands\n"
606     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n";
607 
608 const std::string HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE =
609     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
610     "and a continueType with '-c' or '--continue-type' \n"
611     "and a userId with '-u' or '--user-id' \n";
612 
613 const std::string HELP_MSG_IS_BUNDLE_INSTALLED =
614     "usage: bundle_test_tool getrm <options>\n"
615     "eg:bundle_test_tool getrm -m <module-name> -n <bundle-name> \n"
616     "options list:\n"
617     "  -h, --help                             list available commands\n"
618     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
619     "  -u, --user-id <user-id>                specify a user id\n"
620     "  -a, --app-index <app-index>            specify a app index\n";
621 
622 const std::string HELP_MSG_GET_BUNDLENAME_BY_APPID =
623     "usage: bundle_test_tool getBundleNameByAppId <options>\n"
624     "eg:bundle_test_tool getBundleNameByAppId -a <app-id>\n"
625     "options list:\n"
626     "  -a, --app-id <app-id>            specify a app index or app identifier\n";
627 
628 const std::string HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID =
629     "usage: bundle_test_tool GetSimpleAppInfoForUid <options>\n"
630     "eg:bundle_test_tool getSimpleAppInfoForUid -u <uid>,<uid>,<uid>...\n"
631     "options list:\n"
632     "  -u, --uid  <uid>         specify uid of the application\n";
633 
634 const std::string HELP_MSG_UNINSTALL_PREINSTALL_BUNDLE =
635     "usage: bundle_test_tool uninstallPreInstallBundle <options>\n"
636     "options list:\n"
637     "  -h, --help                             list available commands\n"
638     "  -u, --user-id <user-id>                specify a user id\n"
639     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n"
640     "  -m, --module-name <module-name>        specify module name of the application\n"
641     "  -f, --forced <user-id>                 force uninstall\n";
642 
643 const std::string HELP_MSG_GET_ASSET_ACCESS_GROUPS =
644     "usage: bundle_test_tool getAssetAccessGroups <options>\n"
645     "eg:bundle_test_tool getAssetAccessGroups -n <bundle-name>\n"
646     "options list:\n"
647     "  -h, --help                             list available commands\n"
648     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n";
649 
650 const std::string HELP_MSG_SET_APP_DISTRIBUTION_TYPES =
651     "usage: bundle_test_tool setAppDistributionTypes <options>\n"
652     "eg:bundle_test_tool setAppDistributionTypes -a <appDistributionTypes>\n"
653     "options list:\n"
654     "  -h, --help                             list available commands\n"
655     "  -a, --app_distribution_types <appDistributionTypes>      specify app distribution type list\n";
656 
657 const std::string STRING_IS_BUNDLE_INSTALLED_OK = "IsBundleInstalled is ok \n";
658 const std::string STRING_IS_BUNDLE_INSTALLED_NG = "error: failed to IsBundleInstalled \n";
659 
660 const std::string STRING_GET_BUNDLENAME_BY_APPID_OK = "getBundleNameByAppId is ok \n";
661 const std::string STRING_GET_BUNDLENAME_BY_APPID_NG =
662     "error: failed to getBundleNameByAppId \n";
663 
664 const std::string STRING_GET_SIMPLE_APP_INFO_FOR_UID_OK = "getSimpleAppInfoForUid is ok \n";
665 const std::string STRING_GET_SIMPLE_APP_INFO_FOR_UID_NG =
666     "error: failed to getSimpleAppInfoForUid \n";
667 
668 const std::string STRING_SET_REMOVABLE_OK = "set removable is ok \n";
669 const std::string STRING_SET_REMOVABLE_NG = "error: failed to set removable \n";
670 const std::string STRING_GET_REMOVABLE_OK = "get removable is ok \n";
671 const std::string STRING_GET_REMOVABLE_NG = "error: failed to get removable \n";
672 const std::string STRING_REQUIRE_CORRECT_VALUE =
673     "error: option requires a correct value or note that\n"
674     "the difference in expressions between short option and long option. \n";
675 
676 const std::string STRING_INSTALL_SANDBOX_SUCCESSFULLY = "install sandbox app successfully \n";
677 const std::string STRING_INSTALL_SANDBOX_FAILED = "install sandbox app failed \n";
678 
679 const std::string STRING_UPDATE_APP_EXCRYPTED_STATUS_SUCCESSFULLY = "update app encrypted status successfully \n";
680 const std::string STRING_UPDATE_APP_EXCRYPTED_STATUS_FAILED = "update app encrypted status failed \n";
681 
682 const std::string STRING_UNINSTALL_SANDBOX_SUCCESSFULLY = "uninstall sandbox app successfully\n";
683 const std::string STRING_UNINSTALL_SANDBOX_FAILED = "uninstall sandbox app failed\n";
684 
685 const std::string STRING_DUMP_SANDBOX_FAILED = "dump sandbox app info failed\n";
686 
687 const std::string STRING_GET_STRING_NG = "error: failed to get label \n";
688 
689 const std::string STRING_GET_ICON_NG = "error: failed to get icon \n";
690 
691 const std::string STRING_ADD_RULE_NG = "error: failed to add rule \n";
692 const std::string STRING_GET_RULE_NG = "error: failed to get rule \n";
693 const std::string STRING_DELETE_RULE_NG = "error: failed to delete rule \n";
694 
695 const std::string STRING_DEPLOY_QUICK_FIX_OK = "deploy quick fix successfully\n";
696 const std::string STRING_DEPLOY_QUICK_FIX_NG = "deploy quick fix failed\n";
697 const std::string HELP_MSG_NO_QUICK_FIX_PATH_OPTION = "need a quick fix patch path\n";
698 const std::string STRING_SWITCH_QUICK_FIX_OK = "switch quick fix successfully\n";
699 const std::string STRING_SWITCH_QUICK_FIX_NG = "switch quick fix failed\n";
700 const std::string STRING_DELETE_QUICK_FIX_OK = "delete quick fix successfully\n";
701 const std::string STRING_DELETE_QUICK_FIX_NG = "delete quick fix failed\n";
702 
703 const std::string STRING_SET_DEBUG_MODE_OK = "set debug mode successfully\n";
704 const std::string STRING_SET_DEBUG_MODE_NG = "set debug mode failed\n";
705 
706 const std::string STRING_GET_BUNDLE_STATS_OK = "get bundle stats successfully\n";
707 const std::string STRING_GET_BUNDLE_STATS_NG = "get bundle stats failed\n";
708 
709 const std::string STRING_GET_APP_PROVISION_INFO_OK = "get appProvisionInfo successfully\n";
710 const std::string STRING_GET_APP_PROVISION_INFO_NG = "get appProvisionInfo failed\n";
711 
712 const std::string STRING_QUERY_DATA_GROUP_INFOS_OK = "queryDataGroupInfos successfully\n";
713 const std::string STRING_QUERY_DATA_GROUP_INFOS_NG = "queryDataGroupInfos failed\n";
714 
715 const std::string STRING_GET_GROUP_DIR_OK = "getGroupDir successfully\n";
716 const std::string STRING_GET_GROUP_DIR_NG = "getGroupDir failed\n";
717 
718 const std::string STRING_GET_JSON_PROFILE_NG = "getJsonProfile failed\n";
719 
720 const std::string STRING_GET_UNINSTALLED_BUNDLE_INFO_NG = "getUninstalledBundleInfo failed\n";
721 
722 const std::string STRING_GET_COMPATIBLE_DEVICE_TYPE_OK = "getCompatibleDeviceType successfully\n";
723 const std::string STRING_GET_COMPATIBLE_DEVICE_TYPE_NG = "getCompatibleDeviceType failed\n";
724 
725 const std::string STRING_GET_ODID_OK = "getOdid successfully\n";
726 const std::string STRING_GET_ODID_NG = "getOdid failed\n";
727 
728 const std::string STRING_GET_DIR_OK = "getDirByBundleNameAndAppIndex successfully\n";
729 const std::string STRING_GET_DIR_NG = "getDirByBundleNameAndAppIndex failed\n";
730 
731 const std::string STRING_GET_ALL_BUNDLE_DIRS_OK = "getAllBundleDirs successfully\n";
732 const std::string STRING_GET_ALL_BUNDLE_DIRS_NG = "getAllBundleDirs failed\n";
733 
734 const std::string STRING_GET_ALL_BUNDLE_CACHE_STAT_OK = "getAllBundleCacheStat successfully\n";
735 const std::string STRING_GET_ALL_BUNDLE_CACHE_STAT_NG = "getAllBundleCacheStat failed\n";
736 
737 const std::string STRING_CLEAN_ALL_BUNDLE_CACHE_OK = "cleanAllBundleCache successfully\n";
738 const std::string STRING_CLEAN_ALL_BUNDLE_CACHE_NG = "cleanAllBundleCache failed\n";
739 
740 const std::string STRING_GET_UID_BY_BUNDLENAME_NG = "getUidByBundleName failed\n";
741 
742 const std::string STRING_IMPLICIT_QUERY_SKILL_URI_INFO_NG =
743     "implicitQuerySkillUriInfo failed\n";
744 
745 const std::string STRING_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE_NG =
746     "queryAbilityInfoByContinueType failed\n";
747 
748 const std::string HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION =
749     "error: you must specify a control type with '-n' or '--network-id' \n"
750     "and a accessTokenId with '-a' or '--access-token-id' \n";
751 
752 const std::string GET_DISTRIBUTED_BUNDLE_NAME_COMMAND_NAME = "getDistributedBundleName";
753 
754 const std::string STRING_GET_DISTRIBUTED_BUNDLE_NAME_OK = "get distributedBundleName successfully\n";
755 const std::string STRING_GET_DISTRIBUTED_BUNDLE_NAME_NG = "get distributedBundleName failed\n";
756 
757 const std::string STRING_GET_PROXY_DATA_NG = "get proxyData failed";
758 
759 const std::string STRING_UNINSTALL_PREINSTALL_BUNDLE_SUCCESSFULLY = "uninstall preinstall app successfully\n";
760 const std::string STRING_UNINSTALL_PREINSTALL_BUNDLE_FAILED = "uninstall preinstall app failed\n";
761 
762 const std::string STRING_GET_ASSET_ACCESS_GROUPS_OK = "getAssetAccessGroups successfully\n";
763 const std::string STRING_GET_ASSET_ACCESS_GROUPS_NG = "getAssetAccessGroups failed\n";
764 
765 const std::string STRING_SET_APP_DISTRIBUTION_TYPES_OK = "setAppDistributionTypes successfully\n";
766 const std::string STRING_SET_APP_DISTRIBUTION_TYPES_NG = "setAppDistributionTypes failed\n";
767 
768 const std::string GET_BUNDLE_STATS_ARRAY[] = {
769     "app data size: ",
770     "user data size: ",
771     "distributed data size: ",
772     "database size: ",
773     "cache size: "
774 };
775 
776 const std::string GET_RM = "getrm";
777 const std::string SET_RM = "setrm";
778 const std::string INSTALL_SANDBOX = "installSandbox";
779 const std::string UNINSTALL_SANDBOX = "uninstallSandbox";
780 const std::string DUMP_SANDBOX = "dumpSandbox";
781 const std::string UNINSTALL_PREINSTALL_BUNDLE = "uninstallPreInstallBundle";
782 
783 const std::string SHORT_OPTIONS = "hn:m:a:d:u:i:";
784 const struct option LONG_OPTIONS[] = {
785     {"help", no_argument, nullptr, 'h'},
786     {"bundle-name", required_argument, nullptr, 'n'},
787     {"module-name", required_argument, nullptr, 'm'},
788     {"ability-name", required_argument, nullptr, 'a'},
789     {"device-id", required_argument, nullptr, 'd'},
790     {"user-id", required_argument, nullptr, 'u'},
791     {"is-removable", required_argument, nullptr, 'i'},
792     {nullptr, 0, nullptr, 0},
793 };
794 
795 const std::string SHORT_OPTIONS_IS_BUNDLE_INSTALLED = "hn:u:a:";
796 const struct option LONG_OPTIONS_IS_BUNDLE_INSTALLED[] = {
797     {"help", no_argument, nullptr, 'h'},
798     {"bundle-name", required_argument, nullptr, 'n'},
799     {"user-id", required_argument, nullptr, 'u'},
800     {"app-index", required_argument, nullptr, 'a'},
801     {nullptr, 0, nullptr, 0},
802 };
803 
804 const std::string SHORT_OPTIONS_GET_BUNDLENAME_BY_APPID = "ha:";
805 const struct option LONG_OPTIONS_GET_BUNDLENAME_BY_APPID[] = {
806     {"help", no_argument, nullptr, 'h'},
807     {"app-id", required_argument, nullptr, 'a'},
808     {nullptr, 0, nullptr, 0},
809 };
810 
811 const std::string SHORT_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID = "hu:";
812 const struct option LONG_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID[] = {
813     {"help", no_argument, nullptr, 'h'},
814     {"uid", required_argument, nullptr, 'u'},
815     {nullptr, 0, nullptr, 0},
816 };
817 
818 const std::string SHORT_OPTIONS_SANDBOX = "hn:d:u:a:";
819 const struct option LONG_OPTIONS_SANDBOX[] = {
820     {"help", no_argument, nullptr, 'h'},
821     {"bundle-name", required_argument, nullptr, 'n'},
822     {"user-id", required_argument, nullptr, 'u'},
823     {"dlp-type", required_argument, nullptr, 'd'},
824     {"app-index", required_argument, nullptr, 'a'},
825     {nullptr, 0, nullptr, 0},
826 };
827 
828 const std::string SHORT_OPTIONS_GET = "hn:m:u:i:d:";
829 const struct option LONG_OPTIONS_GET[] = {
830     {"help", no_argument, nullptr, 'h'},
831     {"bundle-name", required_argument, nullptr, 'n'},
832     {"module-name", required_argument, nullptr, 'm'},
833     {"user-id", required_argument, nullptr, 'u'},
834     {"id", required_argument, nullptr, 'i'},
835     {"density", required_argument, nullptr, 'd'},
836     {nullptr, 0, nullptr, 0},
837 };
838 
839 const std::string SHORT_OPTIONS_RULE = "ha:c:n:e:r:t:u:";
840 const struct option LONG_OPTIONS_RULE[] = {
841     {"help", no_argument, nullptr, 'h'},
842     {"app-id", required_argument, nullptr, 'a'},
843     {"control-rule", required_argument, nullptr, 'c'},
844     {"bundle-name", required_argument, nullptr, 'n'},
845     {"bundle-name", required_argument, nullptr, 'n'},
846     {"euid", required_argument, nullptr, 'e'},
847     {"control-rule-type", required_argument, nullptr, 't'},
848     {"user-id", required_argument, nullptr, 'u'},
849     {nullptr, 0, nullptr, 0},
850 };
851 
852 const std::string SHORT_OPTIONS_AUTO_CLEAN_CACHE = "hs:";
853 const struct option LONG_OPTIONS_AUTO_CLEAN_CACHE[] = {
854     {"help", no_argument, nullptr, 'h'},
855     {"cache-size", required_argument, nullptr, 's'},
856     {nullptr, 0, nullptr, 0},
857 };
858 
859 const std::string SHORT_OPTIONS_UPDATE_APP_EXCRYPTED_STATUS = "hn:e:a:";
860 const struct option LONG_OPTIONS_UPDATE_APP_EXCRYPTED_STATUS[] = {
861     {"help", no_argument, nullptr, 'h'},
862     {"bundle-name", required_argument, nullptr, 'n'},
863     {"existed", required_argument, nullptr, 'e'},
864     {"app-index", required_argument, nullptr, 'a'},
865     {nullptr, 0, nullptr, 0},
866 };
867 
868 const std::string SHORT_OPTIONS_QUICK_FIX = "hp:n:e:d:";
869 const struct option LONG_OPTIONS_QUICK_FIX[] = {
870     {"help", no_argument, nullptr, 'h'},
871     {"patch-path", required_argument, nullptr, 'p'},
872     {"bundle-name", required_argument, nullptr, 'n'},
873     {"enable", required_argument, nullptr, 'e'},
874     {"debug", required_argument, nullptr, 'd'},
875     {nullptr, 0, nullptr, 0},
876 };
877 
878 const std::string SHORT_OPTIONS_DEBUG_MODE = "he:";
879 const struct option LONG_OPTIONS_DEBUG_MODE[] = {
880     {"help", no_argument, nullptr, 'h'},
881     {"enable", required_argument, nullptr, 'e'},
882     {nullptr, 0, nullptr, 0},
883 };
884 
885 const std::string SHORT_OPTIONS_GET_BUNDLE_STATS = "hn:u:a:";
886 const struct option LONG_OPTIONS_GET_BUNDLE_STATS[] = {
887     {"help", no_argument, nullptr, 'h'},
888     {"bundle-name", required_argument, nullptr, 'n'},
889     {"user-id", required_argument, nullptr, 'u'},
890     {"app-index", required_argument, nullptr, 'a'},
891     {nullptr, 0, nullptr, 0},
892 };
893 
894 const std::string SHORT_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME = "hn:a:";
895 const struct option LONG_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME[] = {
896     {"help", no_argument, nullptr, 'h'},
897     {"network-id", required_argument, nullptr, 'n'},
898     {"access-token-id", required_argument, nullptr, 'a'},
899     {nullptr, 0, nullptr, 0},
900 };
901 
902 const std::string SHORT_OPTIONS_BUNDLE_EVENT_CALLBACK = "hou:";
903 const struct option LONG_OPTIONS_BUNDLE_EVENT_CALLBACK[] = {
904     {"help", no_argument, nullptr, 'h'},
905     {"onlyUnregister", no_argument, nullptr, 'o'},
906     {"uid", required_argument, nullptr, 'u'},
907     {nullptr, 0, nullptr, 0},
908 };
909 
910 const std::string SHORT_OPTIONS_RESET_AOT_COMPILE_StATUS = "b:m:t:u:";
911 const struct option LONG_OPTIONS_RESET_AOT_COMPILE_StATUS[] = {
912     {"help", no_argument, nullptr, 'h'},
913     {"bundle-name", required_argument, nullptr, 'b'},
914     {"module-name", required_argument, nullptr, 'm'},
915     {"trigger-mode", required_argument, nullptr, 't'},
916     {"uid", required_argument, nullptr, 'u'},
917     {nullptr, 0, nullptr, 0},
918 };
919 
920 const std::string SHORT_OPTIONS_PROXY_DATA = "hn:m:u:";
921 const struct option LONG_OPTIONS_PROXY_DATA[] = {
922     {"help", no_argument, nullptr, 'h'},
923     {"bundle-name", required_argument, nullptr, 'n'},
924     {"module-name", required_argument, nullptr, 'm'},
925     {"user-id", required_argument, nullptr, 'u'},
926     {nullptr, 0, nullptr, 0},
927 };
928 
929 const std::string SHORT_OPTIONS_ALL_PROXY_DATA = "hu:";
930 const struct option LONG_OPTIONS_ALL_PROXY_DATA[] = {
931     {"help", no_argument, nullptr, 'h'},
932     {"user-id", required_argument, nullptr, 'u'},
933     {nullptr, 0, nullptr, 0},
934 };
935 
936 const std::string SHORT_OPTIONS_GET_UID_BY_BUNDLENAME = "hn:u:a:";
937 const struct option LONG_OPTIONS_GET_UID_BY_BUNDLENAME[] = {
938     {"help", no_argument, nullptr, 'h'},
939     {"bundle-name", required_argument, nullptr, 'n'},
940     {"user-id", required_argument, nullptr, 'u'},
941     {"app-index", required_argument, nullptr, 'a'},
942     {nullptr, 0, nullptr, 0},
943 };
944 
945 const std::string SHORT_OPTIONS_MIME = "ha:e:m:n:t:";
946 const struct option LONG_OPTIONS_MIME[] = {
947     {"help", no_argument, nullptr, 'h'},
948     {"ability-name", required_argument, nullptr, 'a'},
949     {"ext-name", required_argument, nullptr, 'e'},
950     {"module-name", required_argument, nullptr, 'm'},
951     {"bundle-name", required_argument, nullptr, 'n'},
952     {"mime-type", required_argument, nullptr, 't'},
953     {nullptr, 0, nullptr, 0},
954 };
955 
956 const std::string SHORT_OPTIONS_GET_GROUP_DIR = "hd:";
957 const struct option LONG_OPTIONS_GET_GROUP_DIR[] = {
958     {"help", no_argument, nullptr, 'h'},
959     {"data-group-id", required_argument, nullptr, 'd'},
960     {nullptr, 0, nullptr, 0},
961 };
962 
963 const std::string SHORT_OPTIONS_GET_JSON_PROFILE = "hp:n:m:u:";
964 const struct option LONG_OPTIONS_GET_JSON_PROFILE[] = {
965     {"help", no_argument, nullptr, 'h'},
966     {"profile-type", required_argument, nullptr, 'p'},
967     {"bundle-name", required_argument, nullptr, 'n'},
968     {"module-name", required_argument, nullptr, 'm'},
969     {"user-id", required_argument, nullptr, 'u'},
970     {nullptr, 0, nullptr, 0},
971 };
972 
973 const std::string SHORT_OPTIONS_UNINSTALLED_BUNDLE_INFO = "hn:";
974 const struct option LONG_OPTIONS_UNINSTALLED_BUNDLE_INFO[] = {
975     {"help", no_argument, nullptr, 'h'},
976     {"bundle-name", required_argument, nullptr, 'n'},
977     {nullptr, 0, nullptr, 0},
978 };
979 
980 const std::string SHORT_OPTIONS_GET_ODID = "hu:";
981 const struct option LONG_OPTIONS_GET_ODID[] = {
982     {"help", no_argument, nullptr, 'h'},
983     {"uid", required_argument, nullptr, 'u'},
984 };
985 
986 const std::string SHORT_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO = "hn:a:e:u:t:";
987 const struct option LONG_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO[] = {
988     {"help", no_argument, nullptr, 'h'},
989     {"bundle-name", required_argument, nullptr, 'n'},
990     {"action", required_argument, nullptr, 'a'},
991     {"entity", required_argument, nullptr, 'e'},
992     {"uri", required_argument, nullptr, 'u'},
993     {"type", required_argument, nullptr, 't'},
994     {nullptr, 0, nullptr, 0},
995 };
996 
997 const std::string SHORT_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE = "hn:c:u:";
998 const struct option LONG_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE[] = {
999     {"help", no_argument, nullptr, 'h'},
1000     {"bundle-name", required_argument, nullptr, 'n'},
1001     {"continueType", required_argument, nullptr, 'c'},
1002     {"userId", required_argument, nullptr, 'u'},
1003     {nullptr, 0, nullptr, 0},
1004 };
1005 
1006 const std::string SHORT_OPTIONS_GET_COMPATIBLE_DEVICE_TYPE = "hn:";
1007 const struct option LONG_OPTIONS_GET_COMPATIBLE_DEVICE_TYPE[] = {
1008     {"help", no_argument, nullptr, 'h'},
1009     {"bundle-name", required_argument, nullptr, 'n'},
1010     {nullptr, 0, nullptr, 0},
1011 };
1012 
1013 const std::string SHORT_OPTIONS_GET_ALL_BUNDLE_DIRS = "hu:";
1014 const struct option LONG_OPTIONS_GET_ALL_BUNDLE_DIRS[] = {
1015     {"help", no_argument, nullptr, 'h'},
1016     {"userId", required_argument, nullptr, 'u'},
1017     {nullptr, 0, nullptr, 0},
1018 };
1019 
1020 const std::string SHORT_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT = "hu:";
1021 const struct option LONG_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT[] = {
1022     {"help", no_argument, nullptr, 'h'},
1023     {"uid", required_argument, nullptr, 'u'},
1024     {nullptr, 0, nullptr, 0},
1025 };
1026 
1027 const std::string SHORT_OPTIONS_CLEAN_ALL_BUNDLE_CACHE = "hu:";
1028 const struct option LONG_OPTIONS_CLEAN_ALL_BUNDLE_CACHE[] = {
1029     {"help", no_argument, nullptr, 'h'},
1030     {"userId", required_argument, nullptr, 'u'},
1031     {nullptr, 0, nullptr, 0},
1032 };
1033 
1034 const std::string SHORT_OPTIONS_GET_DIR = "hn:a:";
1035 const struct option LONG_OPTIONS_GET_DIR[] = {
1036     {"help", no_argument, nullptr, 'h'},
1037     {"bundle-name", required_argument, nullptr, 'n'},
1038     {"app-index", required_argument, nullptr, 'a'},
1039     {nullptr, 0, nullptr, 0},
1040 };
1041 
1042 const std::string SHORT_OPTIONS_PREINSTALL = "hn:m:u:f:";
1043 const struct option LONG_OPTIONS_PREINSTALL[] = {
1044     {"help", no_argument, nullptr, 'h'},
1045     {"bundle-name", required_argument, nullptr, 'n'},
1046     {"module-name", required_argument, nullptr, 'm'},
1047     {"user-id", required_argument, nullptr, 'u'},
1048     {"forced", required_argument, nullptr, 'i'},
1049     {nullptr, 0, nullptr, 0},
1050 };
1051 
1052 const std::string SHORT_OPTIONS_GET_ASSET_ACCESS_GROUPS = "hn:";
1053 const struct option LONG_OPTIONS_GET_ASSET_ACCESS_GROUPS[] = {
1054     {"help", no_argument, nullptr, 'h'},
1055     {"bundle-name", required_argument, nullptr, 'n'},
1056     {nullptr, 0, nullptr, 0},
1057 };
1058 
1059 const std::string SHORT_OPTIONS_SET_APP_DISTRIBUTION_TYPES = "ha:";
1060 const struct option LONG_OPTIONS_SET_APP_DISTRIBUTION_TYPES[] = {
1061     {"help", no_argument, nullptr, 'h'},
1062     {"app-distribution-types", required_argument, nullptr, 'a'},
1063     {nullptr, 0, nullptr, 0},
1064 };
1065 
1066 }  // namespace
1067 
1068 class ProcessCacheCallbackImpl : public ProcessCacheCallbackHost {
1069 public:
ProcessCacheCallbackImpl()1070     ProcessCacheCallbackImpl() {}
~ProcessCacheCallbackImpl()1071     ~ProcessCacheCallbackImpl() {}
1072     bool WaitForCleanCompletion();
1073     bool WaitForStatCompletion();
1074     void OnGetAllBundleCacheFinished(uint64_t cacheStat) override;
1075     void OnCleanAllBundleCacheFinished(int32_t result) override;
GetCacheStat()1076     uint64_t GetCacheStat()
1077     {
1078         return cacheSize_;
1079     }
GetDelRet()1080     int32_t GetDelRet()
1081     {
1082         return cleanRet_;
1083     }
1084 private:
1085     std::mutex mutex_;
1086     bool complete_ = false;
1087     int32_t cleanRet_ = 0;
1088     uint64_t cacheSize_ = 0;
1089     std::promise<void> clean_;
1090     std::future<void> cleanFuture_ = clean_.get_future();
1091     std::promise<void> stat_;
1092     std::future<void> statFuture_ = stat_.get_future();
1093     DISALLOW_COPY_AND_MOVE(ProcessCacheCallbackImpl);
1094 };
1095 
OnGetAllBundleCacheFinished(uint64_t cacheStat)1096 void ProcessCacheCallbackImpl::OnGetAllBundleCacheFinished(uint64_t cacheStat)
1097 {
1098     std::lock_guard<std::mutex> lock(mutex_);
1099     if (!complete_) {
1100         complete_ = true;
1101         cacheSize_ = cacheStat;
1102         stat_.set_value();
1103     }
1104 }
1105 
OnCleanAllBundleCacheFinished(int32_t result)1106 void ProcessCacheCallbackImpl::OnCleanAllBundleCacheFinished(int32_t result)
1107 {
1108     std::lock_guard<std::mutex> lock(mutex_);
1109     if (!complete_) {
1110         complete_ = true;
1111         cleanRet_ = result;
1112         clean_.set_value();
1113     }
1114 }
1115 
WaitForCleanCompletion()1116 bool ProcessCacheCallbackImpl::WaitForCleanCompletion()
1117 {
1118     if (cleanFuture_.wait_for(std::chrono::seconds(MAX_WAITING_TIME)) == std::future_status::ready) {
1119         return true;
1120     }
1121     return false;
1122 }
1123 
WaitForStatCompletion()1124 bool ProcessCacheCallbackImpl::WaitForStatCompletion()
1125 {
1126     if (statFuture_.wait_for(std::chrono::seconds(MAX_WAITING_TIME)) == std::future_status::ready) {
1127         return true;
1128     }
1129     return false;
1130 }
1131 
BundleEventCallbackImpl()1132 BundleEventCallbackImpl::BundleEventCallbackImpl()
1133 {
1134     APP_LOGI("create BundleEventCallbackImpl");
1135 }
1136 
~BundleEventCallbackImpl()1137 BundleEventCallbackImpl::~BundleEventCallbackImpl()
1138 {
1139     APP_LOGI("destroy BundleEventCallbackImpl");
1140 }
1141 
OnReceiveEvent(const EventFwk::CommonEventData eventData)1142 void BundleEventCallbackImpl::OnReceiveEvent(const EventFwk::CommonEventData eventData)
1143 {
1144     const Want &want = eventData.GetWant();
1145     std::string bundleName = want.GetElement().GetBundleName();
1146     std::string moduleName = want.GetElement().GetModuleName();
1147     APP_LOGI("OnReceiveEvent, bundleName:%{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
1148 }
1149 
BundleTestTool(int argc,char * argv[])1150 BundleTestTool::BundleTestTool(int argc, char *argv[]) : ShellCommand(argc, argv, TOOL_NAME)
1151 {}
1152 
~BundleTestTool()1153 BundleTestTool::~BundleTestTool()
1154 {}
1155 
CreateCommandMap()1156 ErrCode BundleTestTool::CreateCommandMap()
1157 {
1158     commandMap_ = {
1159         {"help", std::bind(&BundleTestTool::RunAsHelpCommand, this)},
1160         {"check", std::bind(&BundleTestTool::RunAsCheckCommand, this)},
1161         {"setrm", std::bind(&BundleTestTool::RunAsSetRemovableCommand, this)},
1162         {"getrm", std::bind(&BundleTestTool::RunAsGetRemovableCommand, this)},
1163         {"installSandbox", std::bind(&BundleTestTool::RunAsInstallSandboxCommand, this)},
1164         {"uninstallSandbox", std::bind(&BundleTestTool::RunAsUninstallSandboxCommand, this)},
1165         {"dumpSandbox", std::bind(&BundleTestTool::RunAsDumpSandboxCommand, this)},
1166         {"getStr", std::bind(&BundleTestTool::RunAsGetStringCommand, this)},
1167         {"getIcon", std::bind(&BundleTestTool::RunAsGetIconCommand, this)},
1168         {"addAppInstallRule", std::bind(&BundleTestTool::RunAsAddInstallRuleCommand, this)},
1169         {"getAppInstallRule", std::bind(&BundleTestTool::RunAsGetInstallRuleCommand, this)},
1170         {"deleteAppInstallRule", std::bind(&BundleTestTool::RunAsDeleteInstallRuleCommand, this)},
1171         {"cleanAppInstallRule", std::bind(&BundleTestTool::RunAsCleanInstallRuleCommand, this)},
1172         {"addAppRunningRule", std::bind(&BundleTestTool::RunAsAddAppRunningRuleCommand, this)},
1173         {"deleteAppRunningRule", std::bind(&BundleTestTool::RunAsDeleteAppRunningRuleCommand, this)},
1174         {"cleanAppRunningRule", std::bind(&BundleTestTool::RunAsCleanAppRunningRuleCommand, this)},
1175         {"getAppRunningControlRule", std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleCommand, this)},
1176         {"getAppRunningControlRuleResult",
1177             std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleResultCommand, this)},
1178         {"deployQuickFix", std::bind(&BundleTestTool::RunAsDeployQuickFix, this)},
1179         {"switchQuickFix", std::bind(&BundleTestTool::RunAsSwitchQuickFix, this)},
1180         {"deleteQuickFix", std::bind(&BundleTestTool::RunAsDeleteQuickFix, this)},
1181         {"setDebugMode", std::bind(&BundleTestTool::RunAsSetDebugMode, this)},
1182         {"getBundleStats", std::bind(&BundleTestTool::RunAsGetBundleStats, this)},
1183         {"getAppProvisionInfo", std::bind(&BundleTestTool::RunAsGetAppProvisionInfo, this)},
1184         {"getDistributedBundleName", std::bind(&BundleTestTool::RunAsGetDistributedBundleName, this)},
1185         {"eventCB", std::bind(&BundleTestTool::HandleBundleEventCallback, this)},
1186         {"resetAOTCompileStatus", std::bind(&BundleTestTool::ResetAOTCompileStatus, this)},
1187         {"sendCommonEvent", std::bind(&BundleTestTool::SendCommonEvent, this)},
1188         {"getProxyDataInfos", std::bind(&BundleTestTool::RunAsGetProxyDataCommand, this)},
1189         {"getAllProxyDataInfos", std::bind(&BundleTestTool::RunAsGetAllProxyDataCommand, this)},
1190         {"setExtNameOrMimeToApp", std::bind(&BundleTestTool::RunAsSetExtNameOrMIMEToAppCommand, this)},
1191         {"delExtNameOrMimeToApp", std::bind(&BundleTestTool::RunAsDelExtNameOrMIMEToAppCommand, this)},
1192         {"queryDataGroupInfos", std::bind(&BundleTestTool::RunAsQueryDataGroupInfos, this)},
1193         {"getGroupDir", std::bind(&BundleTestTool::RunAsGetGroupDir, this)},
1194         {"getJsonProfile", std::bind(&BundleTestTool::RunAsGetJsonProfile, this)},
1195         {"getUninstalledBundleInfo", std::bind(&BundleTestTool::RunAsGetUninstalledBundleInfo, this)},
1196         {"getOdid", std::bind(&BundleTestTool::RunAsGetOdid, this)},
1197         {"getUidByBundleName", std::bind(&BundleTestTool::RunGetUidByBundleName, this)},
1198         {"implicitQuerySkillUriInfo",
1199             std::bind(&BundleTestTool::RunAsImplicitQuerySkillUriInfo, this)},
1200         {"queryAbilityInfoByContinueType",
1201             std::bind(&BundleTestTool::RunAsQueryAbilityInfoByContinueType, this)},
1202         {"cleanBundleCacheFilesAutomatic",
1203             std::bind(&BundleTestTool::RunAsCleanBundleCacheFilesAutomaticCommand, this)},
1204         {"getContinueBundleName",
1205             std::bind(&BundleTestTool::RunAsGetContinueBundleName, this)},
1206         {"updateAppEncryptedStatus",
1207             std::bind(&BundleTestTool::RunAsUpdateAppEncryptedStatus, this)},
1208         {"getDirByBundleNameAndAppIndex",
1209             std::bind(&BundleTestTool::RunAsGetDirByBundleNameAndAppIndex, this)},
1210         {"getAllBundleDirs",
1211             std::bind(&BundleTestTool::RunAsGetAllBundleDirs, this)},
1212         {"getAllBundleCacheStat",
1213             std::bind(&BundleTestTool::RunAsGetAllBundleCacheStat, this)},
1214         {"cleanAllBundleCache",
1215             std::bind(&BundleTestTool::RunAsCleanAllBundleCache, this)},
1216         {"isBundleInstalled",
1217             std::bind(&BundleTestTool::RunAsIsBundleInstalled, this)},
1218         {"getCompatibleDeviceType",
1219             std::bind(&BundleTestTool::RunAsGetCompatibleDeviceType, this)},
1220         {"getSimpleAppInfoForUid",
1221             std::bind(&BundleTestTool::RunAsGetSimpleAppInfoForUid, this)},
1222         {"getBundleNameByAppId",
1223             std::bind(&BundleTestTool::RunAsGetBundleNameByAppId, this)},
1224         {"uninstallPreInstallBundle", std::bind(&BundleTestTool::RunAsUninstallPreInstallBundleCommand, this)},
1225         {"getAssetAccessGroups",
1226             std::bind(&BundleTestTool::RunAsGetAssetAccessGroups, this)},
1227         {"setAppDistributionTypes",
1228                 std::bind(&BundleTestTool::RunAsSetAppDistributionTypes, this)}
1229     };
1230 
1231     return OHOS::ERR_OK;
1232 }
1233 
CreateMessageMap()1234 ErrCode BundleTestTool::CreateMessageMap()
1235 {
1236     messageMap_ = BundleCommandCommon::bundleMessageMap_;
1237 
1238     return OHOS::ERR_OK;
1239 }
1240 
Init()1241 ErrCode BundleTestTool::Init()
1242 {
1243     APP_LOGI("BundleTestTool Init()");
1244     ErrCode result = OHOS::ERR_OK;
1245     if (bundleMgrProxy_ == nullptr) {
1246         bundleMgrProxy_ = BundleCommandCommon::GetBundleMgrProxy();
1247         if (bundleMgrProxy_ != nullptr) {
1248             if (bundleInstallerProxy_ == nullptr) {
1249                 bundleInstallerProxy_ = bundleMgrProxy_->GetBundleInstaller();
1250             }
1251         }
1252     }
1253 
1254     if ((bundleMgrProxy_ == nullptr) || (bundleInstallerProxy_ == nullptr) ||
1255         (bundleInstallerProxy_->AsObject() == nullptr)) {
1256         result = OHOS::ERR_INVALID_VALUE;
1257     }
1258 
1259 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
1260     if (distributedBmsProxy_ == nullptr) {
1261         distributedBmsProxy_ = BundleCommandCommon::GetDistributedBundleMgrService();
1262     }
1263 #endif
1264 
1265     return result;
1266 }
1267 
CreateQuickFixMsgMap(std::unordered_map<int32_t,std::string> & quickFixMsgMap)1268 void BundleTestTool::CreateQuickFixMsgMap(std::unordered_map<int32_t, std::string> &quickFixMsgMap)
1269 {
1270     quickFixMsgMap = {
1271         { ERR_OK, Constants::EMPTY_STRING },
1272         { ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR },
1273         { ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR },
1274         { ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED },
1275         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME },
1276         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME },
1277         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME },
1278         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME,
1279             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME },
1280         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME,
1281             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME },
1282         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME },
1283         { ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE },
1284         { ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE },
1285         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST },
1286         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST },
1287         { ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME,
1288             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME },
1289         { ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED,
1290             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED },
1291         { ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED,
1292             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED },
1293         { ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED },
1294         { ERR_APPEXECFWK_OPERATION_TIME_OUT, MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT },
1295         { ERR_APPEXECFWK_FAILED_SERVICE_DIED, MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED },
1296         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE,
1297             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE },
1298         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED },
1299         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED,
1300             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED },
1301         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME },
1302         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO,
1303             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO },
1304         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM },
1305         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR },
1306         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR },
1307         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR,
1308             MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR },
1309         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED },
1310         { ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED },
1311         { ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED,
1312             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED },
1313         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR },
1314         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE },
1315         { ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS },
1316         { ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO,
1317             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO },
1318         { ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED,
1319             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED },
1320         { ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED,
1321             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED },
1322         { ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED,
1323             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED },
1324         { ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB,
1325             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB },
1326         { ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED,
1327             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED }
1328     };
1329 }
1330 
RunAsHelpCommand()1331 ErrCode BundleTestTool::RunAsHelpCommand()
1332 {
1333     resultReceiver_.append(HELP_MSG);
1334 
1335     return OHOS::ERR_OK;
1336 }
1337 
CheckOperation(int userId,std::string deviceId,std::string bundleName,std::string moduleName,std::string abilityName)1338 ErrCode BundleTestTool::CheckOperation(int userId, std::string deviceId, std::string bundleName,
1339     std::string moduleName, std::string abilityName)
1340 {
1341     std::unique_lock<std::mutex> lock(mutex_);
1342     sptr<BundleToolCallbackStub> bundleToolCallbackStub =
1343         new(std::nothrow) BundleToolCallbackStub(cv_, mutex_, dataReady_);
1344     if (bundleToolCallbackStub == nullptr) {
1345         APP_LOGE("bundleToolCallbackStub is null");
1346         return OHOS::ERR_INVALID_VALUE;
1347     }
1348     APP_LOGI("CheckAbilityEnableInstall param: userId:%{public}d, bundleName:%{public}s, moduleName:%{public}s," \
1349         "abilityName:%{public}s", userId, bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
1350     AAFwk::Want want;
1351     want.SetElementName(deviceId, bundleName, abilityName, moduleName);
1352     bool ret = bundleMgrProxy_->CheckAbilityEnableInstall(want, 1, userId, bundleToolCallbackStub);
1353     if (!ret) {
1354         APP_LOGE("CheckAbilityEnableInstall failed");
1355         return OHOS::ERR_OK;
1356     }
1357     APP_LOGI("CheckAbilityEnableInstall wait");
1358     cv_.wait(lock, [this] { return dataReady_; });
1359     dataReady_ = false;
1360     return OHOS::ERR_OK;
1361 }
1362 
RunAsCheckCommand()1363 ErrCode BundleTestTool::RunAsCheckCommand()
1364 {
1365     int counter = 0;
1366     int userId = 100;
1367     std::string deviceId = "";
1368     std::string bundleName = "";
1369     std::string moduleName = "";
1370     std::string abilityName = "";
1371     while (true) {
1372         counter++;
1373         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1374         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1375         if (optind < 0 || optind > argc_) {
1376             return OHOS::ERR_INVALID_VALUE;
1377         }
1378         if (option == -1) {
1379             // When scanning the first argument
1380             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1381                 // 'CheckAbilityEnableInstall' with no option: CheckAbilityEnableInstall
1382                 // 'CheckAbilityEnableInstall' with a wrong argument: CheckAbilityEnableInstall
1383                 APP_LOGD("'CheckAbilityEnableInstall' with no option.");
1384                 return OHOS::ERR_INVALID_VALUE;
1385             }
1386             break;
1387         }
1388         switch (option) {
1389             case 'n': {
1390                 bundleName = optarg;
1391                 break;
1392             }
1393             case 'm': {
1394                 moduleName = optarg;
1395                 break;
1396             }
1397             case 'a': {
1398                 abilityName = optarg;
1399                 break;
1400             }
1401             case 'd': {
1402                 deviceId = optarg;
1403                 break;
1404             }
1405             case 'u': {
1406                 userId = std::stoi(optarg);
1407                 break;
1408             }
1409             default: {
1410                 return OHOS::ERR_INVALID_VALUE;
1411             }
1412         }
1413     }
1414     return CheckOperation(userId, deviceId, bundleName, moduleName, abilityName);
1415 }
1416 
SetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,int isRemovable) const1417 bool BundleTestTool::SetIsRemovableOperation(
1418     const std::string &bundleName, const std::string &moduleName, int isRemovable) const
1419 {
1420     bool enable = true;
1421     if (isRemovable == 0) {
1422         enable = false;
1423     }
1424     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s, enable:%{public}d", bundleName.c_str(), moduleName.c_str(),
1425         enable);
1426     auto ret = bundleMgrProxy_->SetModuleRemovable(bundleName, moduleName, enable);
1427     APP_LOGD("SetModuleRemovable end bundleName: %{public}d", ret);
1428     if (!ret) {
1429         APP_LOGE("SetIsRemovableOperation failed");
1430         return false;
1431     }
1432     return ret;
1433 }
1434 
GetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,std::string & result) const1435 bool BundleTestTool::GetIsRemovableOperation(
1436     const std::string &bundleName, const std::string &moduleName, std::string &result) const
1437 {
1438     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
1439     bool isRemovable = false;
1440     auto ret = bundleMgrProxy_->IsModuleRemovable(bundleName, moduleName, isRemovable);
1441     APP_LOGD("IsModuleRemovable end bundleName: %{public}s, isRemovable:%{public}d", bundleName.c_str(), isRemovable);
1442     result.append("isRemovable: " + std::to_string(isRemovable) + "\n");
1443     if (ret != ERR_OK) {
1444         APP_LOGE("IsModuleRemovable failed, ret: %{public}d", ret);
1445         return false;
1446     }
1447     return true;
1448 }
1449 
CheckRemovableErrorOption(int option,int counter,const std::string & commandName)1450 bool BundleTestTool::CheckRemovableErrorOption(int option, int counter, const std::string &commandName)
1451 {
1452     if (option == -1) {
1453         if (counter == 1) {
1454             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
1455                 // 'bundle_test_tool setrm/getrm' with no option: bundle_test_tool setrm/getrm
1456                 // 'bundle_test_tool setrm/getrm' with a wrong argument: bundle_test_tool setrm/getrm xxx
1457                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
1458                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
1459                 return false;
1460             }
1461         }
1462         return true;
1463     } else if (option == '?') {
1464         switch (optopt) {
1465             case 'i': {
1466                 if (commandName == GET_RM) {
1467                     std::string unknownOption = "";
1468                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1469                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1470                     resultReceiver_.append(unknownOptionMsg);
1471                 } else {
1472                     APP_LOGD("'bundle_test_tool %{public}s -i' with no argument.", commandName.c_str());
1473                     resultReceiver_.append("error: -i option requires a value.\n");
1474                 }
1475                 break;
1476             }
1477             case 'm': {
1478                 APP_LOGD("'bundle_test_tool %{public}s -m' with no argument.", commandName.c_str());
1479                 resultReceiver_.append("error: -m option requires a value.\n");
1480                 break;
1481             }
1482             case 'n': {
1483                 APP_LOGD("'bundle_test_tool %{public}s -n' with no argument.", commandName.c_str());
1484                 resultReceiver_.append("error: -n option requires a value.\n");
1485                 break;
1486             }
1487             default: {
1488                 std::string unknownOption = "";
1489                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1490                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1491                 resultReceiver_.append(unknownOptionMsg);
1492                 break;
1493             }
1494         }
1495     }
1496     return false;
1497 }
1498 
CheckRemovableCorrectOption(int option,const std::string & commandName,int & isRemovable,std::string & name)1499 bool BundleTestTool::CheckRemovableCorrectOption(
1500     int option, const std::string &commandName, int &isRemovable, std::string &name)
1501 {
1502     bool ret = true;
1503     switch (option) {
1504         case 'h': {
1505             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1506             ret = false;
1507             break;
1508         }
1509         case 'n': {
1510             name = optarg;
1511             APP_LOGD("'bundle_test_tool %{public}s -n %{public}s'", commandName.c_str(), argv_[optind - 1]);
1512             break;
1513         }
1514         case 'i': {
1515             if (commandName == GET_RM) {
1516                 std::string unknownOption = "";
1517                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1518                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1519                 resultReceiver_.append(unknownOptionMsg);
1520                 ret = false;
1521             } else if (OHOS::StrToInt(optarg, isRemovable)) {
1522                 APP_LOGD("'bundle_test_tool %{public}s -i isRemovable:%{public}d, %{public}s'",
1523                     commandName.c_str(), isRemovable, argv_[optind - 1]);
1524             } else {
1525                 APP_LOGE("bundle_test_tool setrm with error %{private}s", optarg);
1526                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1527                 ret = false;
1528             }
1529             break;
1530         }
1531         case 'm': {
1532             name = optarg;
1533             APP_LOGD("'bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s'",
1534                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1535             break;
1536         }
1537         default: {
1538             std::string unknownOption = "";
1539             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1540             APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1541             resultReceiver_.append(unknownOptionMsg);
1542             ret = false;
1543             break;
1544         }
1545     }
1546     return ret;
1547 }
1548 
RunAsSetRemovableCommand()1549 ErrCode BundleTestTool::RunAsSetRemovableCommand()
1550 {
1551     int result = OHOS::ERR_OK;
1552     int counter = 0;
1553     int isRemovable = 0;
1554     std::string commandName = SET_RM;
1555     std::string name = "";
1556     std::string bundleName = "";
1557     std::string moduleName = "";
1558     APP_LOGD("RunAsSetCommand is start");
1559     while (true) {
1560         counter++;
1561         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1562         if (optind < 0 || optind > argc_) {
1563             return OHOS::ERR_INVALID_VALUE;
1564         }
1565         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d, argv_[optind - 1]:%{public}s", option,
1566             optopt, optind, argv_[optind - 1]);
1567         if (option == -1 || option == '?') {
1568             result = !CheckRemovableErrorOption(option, counter, commandName)? OHOS::ERR_INVALID_VALUE : result;
1569             break;
1570         }
1571         result = !CheckRemovableCorrectOption(option, commandName, isRemovable, name)
1572             ? OHOS::ERR_INVALID_VALUE : result;
1573         moduleName = option == 'm' ? name : moduleName;
1574         bundleName = option == 'n' ? name : bundleName;
1575     }
1576     if (result == OHOS::ERR_OK) {
1577         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
1578             APP_LOGD("'bundle_test_tool setrm' with not enough option.");
1579             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
1580             result = OHOS::ERR_INVALID_VALUE;
1581         }
1582     }
1583     if (result != OHOS::ERR_OK) {
1584         resultReceiver_.append(HELP_MSG_SET);
1585     } else {
1586         bool setResult = false;
1587         setResult = SetIsRemovableOperation(bundleName, moduleName, isRemovable);
1588         APP_LOGD("'bundle_test_tool setrm' isRemovable is %{public}d", isRemovable);
1589         resultReceiver_ = setResult ? STRING_SET_REMOVABLE_OK : STRING_SET_REMOVABLE_NG;
1590     }
1591     return result;
1592 }
1593 
RunAsGetRemovableCommand()1594 ErrCode BundleTestTool::RunAsGetRemovableCommand()
1595 {
1596     int result = OHOS::ERR_OK;
1597     int counter = 0;
1598     std::string commandName = GET_RM;
1599     std::string name = "";
1600     std::string bundleName = "";
1601     std::string moduleName = "";
1602     APP_LOGD("RunAsGetRemovableCommand is start");
1603     while (true) {
1604         counter++;
1605         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1606         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1607         if (optind < 0 || optind > argc_) {
1608             return OHOS::ERR_INVALID_VALUE;
1609         }
1610         if (option == -1 || option == '?') {
1611             result = !CheckRemovableErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1612             break;
1613         }
1614         int tempIsRem = 0;
1615         result = !CheckRemovableCorrectOption(option, commandName, tempIsRem, name)
1616             ? OHOS::ERR_INVALID_VALUE : result;
1617         moduleName = option == 'm' ? name : moduleName;
1618         bundleName = option == 'n' ? name : bundleName;
1619     }
1620 
1621     if (result == OHOS::ERR_OK) {
1622         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
1623             APP_LOGD("'bundle_test_tool getrm' with no option.");
1624             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
1625             result = OHOS::ERR_INVALID_VALUE;
1626         }
1627     }
1628 
1629     if (result != OHOS::ERR_OK) {
1630         resultReceiver_.append(HELP_MSG_GET_REMOVABLE);
1631     } else {
1632         std::string results = "";
1633         GetIsRemovableOperation(bundleName, moduleName, results);
1634         if (results.empty()) {
1635             resultReceiver_.append(STRING_GET_REMOVABLE_NG);
1636             return result;
1637         }
1638         resultReceiver_.append(results);
1639     }
1640     return result;
1641 }
1642 
CheckSandboxErrorOption(int option,int counter,const std::string & commandName)1643 bool BundleTestTool::CheckSandboxErrorOption(int option, int counter, const std::string &commandName)
1644 {
1645     if (option == -1) {
1646         if (counter == 1) {
1647             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
1648                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
1649                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
1650                 return false;
1651             }
1652         }
1653         return true;
1654     } else if (option == '?') {
1655         switch (optopt) {
1656             case 'n':
1657             case 'u':
1658             case 'd':
1659             case 'a': {
1660                 if ((commandName != INSTALL_SANDBOX && optopt == 'd') ||
1661                     (commandName == INSTALL_SANDBOX && optopt == 'a')) {
1662                     std::string unknownOption = "";
1663                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1664                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1665                     resultReceiver_.append(unknownOptionMsg);
1666                     break;
1667                 }
1668                 APP_LOGD("'bundle_test_tool %{public}s' -%{public}c with no argument.", commandName.c_str(), optopt);
1669                 resultReceiver_.append("error: option requires a value.\n");
1670                 break;
1671             }
1672             default: {
1673                 std::string unknownOption = "";
1674                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1675                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1676                 resultReceiver_.append(unknownOptionMsg);
1677                 break;
1678             }
1679         }
1680     }
1681     return false;
1682 }
1683 
CheckSandboxCorrectOption(int option,const std::string & commandName,int & data,std::string & bundleName)1684 bool BundleTestTool::CheckSandboxCorrectOption(
1685     int option, const std::string &commandName, int &data, std::string &bundleName)
1686 {
1687     bool ret = true;
1688     switch (option) {
1689         case 'h': {
1690             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1691             ret = false;
1692             break;
1693         }
1694         case 'n': {
1695             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1696             bundleName = optarg;
1697             break;
1698         }
1699         case 'u':
1700         case 'a':
1701         case 'd': {
1702             if ((commandName != INSTALL_SANDBOX && option == 'd') ||
1703                 (commandName == INSTALL_SANDBOX && option == 'a')) {
1704                 std::string unknownOption = "";
1705                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1706                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1707                 resultReceiver_.append(unknownOptionMsg);
1708                 ret = false;
1709                 break;
1710             }
1711 
1712             APP_LOGD("'bundle_test_tool %{public}s %{public}s %{public}s'", commandName.c_str(),
1713                 argv_[optind - OFFSET_REQUIRED_ARGUMENT], optarg);
1714 
1715             if (!OHOS::StrToInt(optarg, data)) {
1716                 if (option == 'u') {
1717                     APP_LOGE("bundle_test_tool %{public}s with error -u %{private}s", commandName.c_str(), optarg);
1718                 } else if (option == 'a') {
1719                     APP_LOGE("bundle_test_tool %{public}s with error -a %{private}s", commandName.c_str(), optarg);
1720                 } else {
1721                     APP_LOGE("bundle_test_tool %{public}s with error -d %{private}s", commandName.c_str(), optarg);
1722                 }
1723                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1724                 ret = false;
1725             }
1726             break;
1727         }
1728         default: {
1729             ret = false;
1730             break;
1731         }
1732     }
1733     return ret;
1734 }
1735 
InstallSandboxOperation(const std::string & bundleName,const int32_t userId,const int32_t dlpType,int32_t & appIndex) const1736 ErrCode BundleTestTool::InstallSandboxOperation(
1737     const std::string &bundleName, const int32_t userId, const int32_t dlpType, int32_t &appIndex) const
1738 {
1739     APP_LOGD("InstallSandboxOperation of bundleName %{public}s, dipType is %{public}d", bundleName.c_str(), dlpType);
1740     return bundleInstallerProxy_->InstallSandboxApp(bundleName, dlpType, userId, appIndex);
1741 }
1742 
RunAsInstallSandboxCommand()1743 ErrCode BundleTestTool::RunAsInstallSandboxCommand()
1744 {
1745     int result = OHOS::ERR_OK;
1746     int counter = 0;
1747     std::string commandName = INSTALL_SANDBOX;
1748     std::string bundleName = "";
1749     int32_t userId = 100;
1750     int32_t dlpType = 0;
1751     while (true) {
1752         counter++;
1753         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1754         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1755         if (optind < 0 || optind > argc_) {
1756             return OHOS::ERR_INVALID_VALUE;
1757         }
1758         if (option == -1 || option == '?') {
1759             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1760             break;
1761         } else if (option == 'u') {
1762             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1763                 OHOS::ERR_INVALID_VALUE : result;
1764         } else {
1765             result = !CheckSandboxCorrectOption(option, commandName, dlpType, bundleName) ?
1766                 OHOS::ERR_INVALID_VALUE : result;
1767         }
1768     }
1769 
1770     if (result == OHOS::ERR_OK && bundleName == "") {
1771         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1772         result = OHOS::ERR_INVALID_VALUE;
1773     } else {
1774         APP_LOGD("installSandbox app bundleName is %{public}s", bundleName.c_str());
1775     }
1776 
1777     if (result != OHOS::ERR_OK) {
1778         resultReceiver_.append(HELP_MSG_INSTALL_SANDBOX);
1779         return result;
1780     }
1781 
1782     int32_t appIndex = 0;
1783     auto ret = InstallSandboxOperation(bundleName, userId, dlpType, appIndex);
1784     if (ret == OHOS::ERR_OK) {
1785         resultReceiver_.append(STRING_INSTALL_SANDBOX_SUCCESSFULLY);
1786     } else {
1787         resultReceiver_.append(STRING_INSTALL_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1788     }
1789     return result;
1790 }
1791 
UninstallSandboxOperation(const std::string & bundleName,const int32_t appIndex,const int32_t userId) const1792 ErrCode BundleTestTool::UninstallSandboxOperation(const std::string &bundleName,
1793     const int32_t appIndex, const int32_t userId) const
1794 {
1795     APP_LOGD("UninstallSandboxOperation of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1796     return bundleInstallerProxy_->UninstallSandboxApp(bundleName, appIndex, userId);
1797 }
1798 
RunAsUninstallSandboxCommand()1799 ErrCode BundleTestTool::RunAsUninstallSandboxCommand()
1800 {
1801     int result = OHOS::ERR_OK;
1802     int counter = 0;
1803     std::string bundleName = "";
1804     std::string commandName = UNINSTALL_SANDBOX;
1805     int32_t userId = 100;
1806     int32_t appIndex = -1;
1807     while (true) {
1808         counter++;
1809         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1810         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1811         if (optind < 0 || optind > argc_) {
1812             return OHOS::ERR_INVALID_VALUE;
1813         }
1814 
1815         if (option == -1 || option == '?') {
1816             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1817             break;
1818         } else if (option == 'u') {
1819             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1820                 OHOS::ERR_INVALID_VALUE : result;
1821         } else {
1822             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1823                 OHOS::ERR_INVALID_VALUE : result;
1824         }
1825     }
1826 
1827     if (result == OHOS::ERR_OK && bundleName == "") {
1828         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1829         result = OHOS::ERR_INVALID_VALUE;
1830     } else {
1831         APP_LOGD("uninstallSandbox app bundleName is %{private}s", bundleName.c_str());
1832     }
1833 
1834     if (result != OHOS::ERR_OK) {
1835         resultReceiver_.append(HELP_MSG_UNINSTALL_SANDBOX);
1836         return result;
1837     }
1838 
1839     auto ret = UninstallSandboxOperation(bundleName, appIndex, userId);
1840     if (ret == ERR_OK) {
1841         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_SUCCESSFULLY);
1842     } else {
1843         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_FAILED + "errCode is " + std::to_string(ret) + "\n");
1844     }
1845     return result;
1846 }
1847 
DumpSandboxBundleInfo(const std::string & bundleName,const int32_t appIndex,const int32_t userId,std::string & dumpResults)1848 ErrCode BundleTestTool::DumpSandboxBundleInfo(const std::string &bundleName, const int32_t appIndex,
1849     const int32_t userId, std::string &dumpResults)
1850 {
1851     APP_LOGD("DumpSandboxBundleInfo of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1852     BundleInfo bundleInfo;
1853     BundleMgrClient client;
1854     auto dumpRet = client.GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo);
1855     if (dumpRet == ERR_OK) {
1856         nlohmann::json jsonObject = bundleInfo;
1857         jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
1858         dumpResults= jsonObject.dump(Constants::DUMP_INDENT);
1859     }
1860     return dumpRet;
1861 }
1862 
RunAsDumpSandboxCommand()1863 ErrCode BundleTestTool::RunAsDumpSandboxCommand()
1864 {
1865     int result = OHOS::ERR_OK;
1866     int counter = 0;
1867     std::string bundleName = "";
1868     std::string commandName = DUMP_SANDBOX;
1869     int32_t userId = 100;
1870     int32_t appIndex = -1;
1871     while (true) {
1872         counter++;
1873         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1874         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1875         if (optind < 0 || optind > argc_) {
1876             return OHOS::ERR_INVALID_VALUE;
1877         }
1878         if (option == -1 || option == '?') {
1879             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1880             break;
1881         } else if (option == 'u') {
1882             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1883                 OHOS::ERR_INVALID_VALUE : result;
1884         } else {
1885             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1886                 OHOS::ERR_INVALID_VALUE : result;
1887         }
1888     }
1889 
1890     if (result == OHOS::ERR_OK && bundleName == "") {
1891         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1892         result = OHOS::ERR_INVALID_VALUE;
1893     } else {
1894         APP_LOGD("dumpSandbox app bundleName is %{public}s", bundleName.c_str());
1895     }
1896 
1897     if (result != OHOS::ERR_OK) {
1898         resultReceiver_.append(HELP_MSG_DUMP_SANDBOX);
1899         return result;
1900     }
1901 
1902     std::string dumpRes = "";
1903     ErrCode ret = DumpSandboxBundleInfo(bundleName, appIndex, userId, dumpRes);
1904     if (ret == ERR_OK) {
1905         resultReceiver_.append(dumpRes + "\n");
1906     } else {
1907         resultReceiver_.append(STRING_DUMP_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1908     }
1909     return result;
1910 }
1911 
StringToInt(std::string optarg,const std::string & commandName,int & temp,bool & result)1912 ErrCode BundleTestTool::StringToInt(
1913     std::string optarg, const std::string &commandName, int &temp, bool &result)
1914 {
1915     try {
1916         temp = std::stoi(optarg);
1917         if (optind > 0 && optind <= argc_) {
1918             APP_LOGD("bundle_test_tool %{public}s -u user-id:%{public}d, %{public}s",
1919                 commandName.c_str(), temp, argv_[optind - 1]);
1920         }
1921     } catch (const std::exception& e) {
1922         std::cerr << e.what() << std::endl;
1923         result = false;
1924     }
1925     return OHOS::ERR_OK;
1926 }
1927 
StringToUnsignedLongLong(std::string optarg,const std::string & commandName,uint64_t & temp,bool & result)1928 ErrCode BundleTestTool::StringToUnsignedLongLong(
1929     std::string optarg, const std::string &commandName, uint64_t &temp, bool &result)
1930 {
1931     try {
1932         APP_LOGI("StringToUnsignedLongLong start, optarg : %{public}s", optarg.c_str());
1933         if ((optarg == "") || (optarg[0] == '0') || (!isdigit(optarg[0]))) {
1934             resultReceiver_.append("error: parameter error, cache size must be greater than 0\n");
1935             return OHOS::ERR_INVALID_VALUE;
1936         }
1937         temp = std::stoull(optarg);
1938     } catch (const std::exception& e) {
1939         std::cerr << e.what() << std::endl;
1940         result = false;
1941     }
1942     return OHOS::ERR_OK;
1943 }
1944 
HandleUnknownOption(const std::string & commandName,bool & ret)1945 bool BundleTestTool::HandleUnknownOption(const std::string &commandName, bool &ret)
1946 {
1947     std::string unknownOption = "";
1948     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1949     APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1950     resultReceiver_.append(unknownOptionMsg);
1951     return ret = false;
1952 }
1953 
CheckGetStringCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1954 bool BundleTestTool::CheckGetStringCorrectOption(
1955     int option, const std::string &commandName, int &temp, std::string &name)
1956 {
1957     bool ret = true;
1958     switch (option) {
1959         case 'h': {
1960             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1961             ret = false;
1962             break;
1963         }
1964         case 'n': {
1965             name = optarg;
1966             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1967             break;
1968         }
1969         case 'm': {
1970             name = optarg;
1971             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1972                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1973             break;
1974         }
1975         case 'c': {
1976             name = optarg;
1977             APP_LOGD("bundle_test_tool %{public}s -m continue-type:%{public}s, %{public}s",
1978                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1979             break;
1980         }
1981         case 'u': {
1982             StringToInt(optarg, commandName, temp, ret);
1983             break;
1984         }
1985         case 'a': {
1986             StringToInt(optarg, commandName, temp, ret);
1987             break;
1988         }
1989         case 'p': {
1990             StringToInt(optarg, commandName, temp, ret);
1991             break;
1992         }
1993         case 'i': {
1994             StringToInt(optarg, commandName, temp, ret);
1995             break;
1996         }
1997         default: {
1998             HandleUnknownOption(commandName, ret);
1999             break;
2000         }
2001     }
2002     return ret;
2003 }
2004 
CheckGetProxyDataCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2005 bool BundleTestTool::CheckGetProxyDataCorrectOption(
2006     int option, const std::string &commandName, int &temp, std::string &name)
2007 {
2008     bool ret = true;
2009     switch (option) {
2010         case 'h': {
2011             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2012             ret = false;
2013             break;
2014         }
2015         case 'n': {
2016             name = optarg;
2017             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
2018             break;
2019         }
2020         case 'm': {
2021             name = optarg;
2022             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
2023                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2024             break;
2025         }
2026         case 'u': {
2027             StringToInt(optarg, commandName, temp, ret);
2028             break;
2029         }
2030         default: {
2031             std::string unknownOption = "";
2032             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2033             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2034             resultReceiver_.append(unknownOptionMsg);
2035             ret = false;
2036             break;
2037         }
2038     }
2039     return ret;
2040 }
2041 
CheckGetAllProxyDataCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2042 bool BundleTestTool::CheckGetAllProxyDataCorrectOption(
2043     int option, const std::string &commandName, int &temp, std::string &name)
2044 {
2045     bool ret = true;
2046     switch (option) {
2047         case 'h': {
2048             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2049             ret = false;
2050             break;
2051         }
2052         case 'u': {
2053             StringToInt(optarg, commandName, temp, ret);
2054             break;
2055         }
2056         default: {
2057             std::string unknownOption = "";
2058             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2059             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2060             resultReceiver_.append(unknownOptionMsg);
2061             ret = false;
2062             break;
2063         }
2064     }
2065     return ret;
2066 }
2067 
RunAsGetProxyDataCommand()2068 ErrCode BundleTestTool::RunAsGetProxyDataCommand()
2069 {
2070     int result = OHOS::ERR_OK;
2071     int counter = 0;
2072     std::string commandName = "getProxyData";
2073     std::string name = "";
2074     std::string bundleName = "";
2075     std::string moduleName = "";
2076     int userId = Constants::ALL_USERID;
2077     APP_LOGD("RunAsGetProxyDataCommand is start");
2078     while (true) {
2079         counter++;
2080         int32_t option = getopt_long(
2081             argc_, argv_, SHORT_OPTIONS_PROXY_DATA.c_str(), LONG_OPTIONS_PROXY_DATA, nullptr);
2082         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2083         if (optind < 0 || optind > argc_) {
2084             return OHOS::ERR_INVALID_VALUE;
2085         }
2086         if (option == -1) {
2087             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2088                 APP_LOGD("bundle_test_tool getProxyData with no option.");
2089                 resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2090                 return OHOS::ERR_INVALID_VALUE;
2091             }
2092             break;
2093         }
2094         int temp = 0;
2095         result = !CheckGetProxyDataCorrectOption(option, commandName, temp, name)
2096                  ? OHOS::ERR_INVALID_VALUE : result;
2097         moduleName = option == 'm' ? name : moduleName;
2098         bundleName = option == 'n' ? name : bundleName;
2099         userId = option == 'u' ? temp : userId;
2100     }
2101 
2102     if (result != OHOS::ERR_OK) {
2103         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2104     } else {
2105         std::vector<ProxyData> proxyDatas;
2106         result = bundleMgrProxy_->GetProxyDataInfos(bundleName, moduleName, proxyDatas, userId);
2107         if (result == ERR_OK) {
2108             nlohmann::json jsonObject = proxyDatas;
2109             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
2110             resultReceiver_.append(results);
2111         } else {
2112             resultReceiver_.append(STRING_GET_PROXY_DATA_NG + " errCode is "+ std::to_string(result) + "\n");
2113         }
2114     }
2115     return result;
2116 }
2117 
RunAsGetAllProxyDataCommand()2118 ErrCode BundleTestTool::RunAsGetAllProxyDataCommand()
2119 {
2120     int result = OHOS::ERR_OK;
2121     int counter = 0;
2122     std::string commandName = "getProxyData";
2123     std::string name = "";
2124     int userId = Constants::ALL_USERID;
2125     APP_LOGD("RunAsGetAllProxyDataCommand is start");
2126     while (true) {
2127         counter++;
2128         int32_t option = getopt_long(
2129             argc_, argv_, SHORT_OPTIONS_ALL_PROXY_DATA.c_str(), LONG_OPTIONS_ALL_PROXY_DATA, nullptr);
2130         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2131         if (optind < 0 || optind > argc_) {
2132             return OHOS::ERR_INVALID_VALUE;
2133         }
2134         if (option == -1) {
2135             break;
2136         }
2137 
2138         int temp = 0;
2139         result = !CheckGetAllProxyDataCorrectOption(option, commandName, temp, name)
2140                  ? OHOS::ERR_INVALID_VALUE : result;
2141         userId = option == 'u' ? temp : userId;
2142     }
2143 
2144     if (result != OHOS::ERR_OK) {
2145         resultReceiver_.append(HELP_MSG_GET_ALL_PROXY_DATA);
2146     } else {
2147         std::vector<ProxyData> proxyDatas;
2148         result = bundleMgrProxy_->GetAllProxyDataInfos(proxyDatas, userId);
2149         if (result == ERR_OK) {
2150             nlohmann::json jsonObject = proxyDatas;
2151             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
2152             resultReceiver_.append(results);
2153         } else {
2154             resultReceiver_.append(STRING_GET_PROXY_DATA_NG + " errCode is "+ std::to_string(result) + "\n");
2155         }
2156     }
2157     return result;
2158 }
2159 
RunAsGetStringCommand()2160 ErrCode BundleTestTool::RunAsGetStringCommand()
2161 {
2162     int result = OHOS::ERR_OK;
2163     int counter = 0;
2164     std::string commandName = "getStr";
2165     std::string name = "";
2166     std::string bundleName = "";
2167     std::string moduleName = "";
2168     int userId = 100;
2169     int labelId = 0;
2170     APP_LOGD("RunAsGetStringCommand is start");
2171     while (true) {
2172         counter++;
2173         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
2174         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2175         if (optind < 0 || optind > argc_) {
2176             return OHOS::ERR_INVALID_VALUE;
2177         }
2178         if (option == -1) {
2179             // When scanning the first argument
2180             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2181                 // 'GetStringById' with no option: GetStringById
2182                 // 'GetStringById' with a wrong argument: GetStringById
2183                 APP_LOGD("bundle_test_tool getStr with no option.");
2184                 resultReceiver_.append(HELP_MSG_NO_GETSTRING_OPTION);
2185                 return OHOS::ERR_INVALID_VALUE;
2186             }
2187             break;
2188         }
2189         int temp = 0;
2190         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
2191             ? OHOS::ERR_INVALID_VALUE : result;
2192         moduleName = option == 'm' ? name : moduleName;
2193         bundleName = option == 'n' ? name : bundleName;
2194         userId = option == 'u' ? temp : userId;
2195         labelId = option == 'i' ? temp : labelId;
2196     }
2197 
2198     if (result != OHOS::ERR_OK) {
2199         resultReceiver_.append(HELP_MSG_GET_STRING);
2200     } else {
2201         std::string results = "";
2202         results = bundleMgrProxy_->GetStringById(bundleName, moduleName, labelId, userId);
2203         if (results.empty()) {
2204             resultReceiver_.append(STRING_GET_STRING_NG);
2205             return result;
2206         }
2207         resultReceiver_.append(results);
2208     }
2209     return result;
2210 }
2211 
CheckExtOrMimeCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2212 bool BundleTestTool::CheckExtOrMimeCorrectOption(
2213     int option, const std::string &commandName, int &temp, std::string &name)
2214 {
2215     bool ret = true;
2216     switch (option) {
2217         case 'h': {
2218             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2219             ret = false;
2220             break;
2221         }
2222         case 'n': {
2223             name = optarg;
2224             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
2225             break;
2226         }
2227         case 'm': {
2228             name = optarg;
2229             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
2230                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2231             break;
2232         }
2233         case 'a': {
2234             name = optarg;
2235             APP_LOGD("bundle_test_tool %{public}s -m ability-name:%{public}s, %{public}s",
2236                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2237             break;
2238         }
2239         case 'e': {
2240             name = optarg;
2241             APP_LOGD("bundle_test_tool %{public}s -m ext-name:%{public}s, %{public}s",
2242                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2243             break;
2244         }
2245         case 't': {
2246             name = optarg;
2247             APP_LOGD("bundle_test_tool %{public}s -m mime-type:%{public}s, %{public}s",
2248                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2249             break;
2250         }
2251         default: {
2252             std::string unknownOption = "";
2253             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2254             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2255             resultReceiver_.append(unknownOptionMsg);
2256             ret = false;
2257             break;
2258         }
2259     }
2260     return ret;
2261 }
2262 
RunAsSetExtNameOrMIMEToAppCommand()2263 ErrCode BundleTestTool::RunAsSetExtNameOrMIMEToAppCommand()
2264 {
2265     int result = OHOS::ERR_OK;
2266     int counter = 0;
2267     std::string commandName = "setExtNameOrMimeToApp";
2268     std::string name = "";
2269     std::string bundleName = "";
2270     std::string moduleName = "";
2271     std::string abilityName = "";
2272     std::string extName = "";
2273     std::string mimeType = "";
2274     APP_LOGD("RunAsSetExtNameOrMIMEToAppCommand is start");
2275     while (true) {
2276         counter++;
2277         int32_t option = getopt_long(
2278             argc_, argv_, SHORT_OPTIONS_MIME.c_str(), LONG_OPTIONS_MIME, nullptr);
2279         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2280         if (optind < 0 || optind > argc_) {
2281             return OHOS::ERR_INVALID_VALUE;
2282         }
2283         if (option == -1) {
2284             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2285                 APP_LOGD("bundle_test_tool RunAsSetExtNameOrMIMEToAppCommand with no option.");
2286                 resultReceiver_.append(HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE);
2287                 return OHOS::ERR_INVALID_VALUE;
2288             }
2289             break;
2290         }
2291         int temp = 0;
2292         result = !CheckExtOrMimeCorrectOption(option, commandName, temp, name)
2293                  ? OHOS::ERR_INVALID_VALUE : result;
2294         moduleName = option == 'm' ? name : moduleName;
2295         bundleName = option == 'n' ? name : bundleName;
2296         abilityName = option == 'a' ? name : abilityName;
2297         extName = option == 'e' ? name : extName;
2298         mimeType = option == 't' ? name : mimeType;
2299     }
2300 
2301     if (result != OHOS::ERR_OK) {
2302         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2303     } else {
2304         result = bundleMgrProxy_->SetExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
2305         if (result == ERR_OK) {
2306             resultReceiver_.append("SetExtNameOrMIMEToApp succeeded,");
2307         } else {
2308             resultReceiver_.append("SetExtNameOrMIMEToApp failed, errCode is "+ std::to_string(result) + "\n");
2309         }
2310     }
2311     return result;
2312 }
2313 
RunAsDelExtNameOrMIMEToAppCommand()2314 ErrCode BundleTestTool::RunAsDelExtNameOrMIMEToAppCommand()
2315 {
2316     int result = OHOS::ERR_OK;
2317     int counter = 0;
2318     std::string commandName = "delExtNameOrMimeToApp";
2319     std::string name = "";
2320     std::string bundleName = "";
2321     std::string moduleName = "";
2322     std::string abilityName = "";
2323     std::string extName = "";
2324     std::string mimeType = "";
2325     APP_LOGD("RunAsDelExtNameOrMIMEToAppCommand is start");
2326     while (true) {
2327         counter++;
2328         int32_t option = getopt_long(
2329             argc_, argv_, SHORT_OPTIONS_MIME.c_str(), LONG_OPTIONS_MIME, nullptr);
2330         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2331         if (optind < 0 || optind > argc_) {
2332             return OHOS::ERR_INVALID_VALUE;
2333         }
2334         if (option == -1) {
2335             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2336                 APP_LOGD("bundle_test_tool RunAsDelExtNameOrMIMEToAppCommand with no option.");
2337                 resultReceiver_.append(HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE);
2338                 return OHOS::ERR_INVALID_VALUE;
2339             }
2340             break;
2341         }
2342         int temp = 0;
2343         result = !CheckExtOrMimeCorrectOption(option, commandName, temp, name)
2344                  ? OHOS::ERR_INVALID_VALUE : result;
2345         moduleName = option == 'm' ? name : moduleName;
2346         bundleName = option == 'n' ? name : bundleName;
2347         abilityName = option == 'a' ? name : abilityName;
2348         extName = option == 'e' ? name : extName;
2349         mimeType = option == 't' ? name : mimeType;
2350     }
2351 
2352     if (result != OHOS::ERR_OK) {
2353         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2354     } else {
2355         result = bundleMgrProxy_->DelExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
2356         if (result == ERR_OK) {
2357             resultReceiver_.append("DelExtNameOrMIMEToApp succeeded");
2358         } else {
2359             resultReceiver_.append("DelExtNameOrMIMEToApp failed, errCode is "+ std::to_string(result) + "\n");
2360         }
2361     }
2362     return result;
2363 }
2364 
CheckGetIconCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2365 bool BundleTestTool::CheckGetIconCorrectOption(
2366     int option, const std::string &commandName, int &temp, std::string &name)
2367 {
2368     bool ret = true;
2369     switch (option) {
2370         case 'h': {
2371             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2372             ret = false;
2373             break;
2374         }
2375         case 'n': {
2376             name = optarg;
2377             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
2378             break;
2379         }
2380         case 'm': {
2381             name = optarg;
2382             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
2383                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
2384             break;
2385         }
2386         case 'u': {
2387             StringToInt(optarg, commandName, temp, ret);
2388             break;
2389         }
2390         case 'i': {
2391             StringToInt(optarg, commandName, temp, ret);
2392             break;
2393         }
2394         case 'd': {
2395             StringToInt(optarg, commandName, temp, ret);
2396             break;
2397         }
2398         default: {
2399             std::string unknownOption = "";
2400             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2401             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2402             resultReceiver_.append(unknownOptionMsg);
2403             ret = false;
2404             break;
2405         }
2406     }
2407     return ret;
2408 }
2409 
RunAsGetIconCommand()2410 ErrCode BundleTestTool::RunAsGetIconCommand()
2411 {
2412     int result = OHOS::ERR_OK;
2413     int counter = 0;
2414     std::string commandName = "getIcon";
2415     std::string name = "";
2416     std::string bundleName = "";
2417     std::string moduleName = "";
2418     int userId = 100;
2419     int iconId = 0;
2420     int density = 0;
2421     APP_LOGD("RunAsGetIconCommand is start");
2422     while (true) {
2423         counter++;
2424         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
2425         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2426         if (optind < 0 || optind > argc_) {
2427             return OHOS::ERR_INVALID_VALUE;
2428         }
2429         if (option == -1) {
2430             // When scanning the first argument
2431             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2432                 // 'GetIconById' with no option: GetStringById
2433                 // 'GetIconById' with a wrong argument: GetStringById
2434                 APP_LOGD("bundle_test_tool getIcon with no option.");
2435                 resultReceiver_.append(HELP_MSG_NO_GETICON_OPTION);
2436                 return OHOS::ERR_INVALID_VALUE;
2437             }
2438             break;
2439         }
2440         int temp = 0;
2441         result = !CheckGetIconCorrectOption(option, commandName, temp, name)
2442             ? OHOS::ERR_INVALID_VALUE : result;
2443         moduleName = option == 'm' ? name : moduleName;
2444         bundleName = option == 'n' ? name : bundleName;
2445         userId = option == 'u' ? temp : userId;
2446         iconId = option == 'i' ? temp : iconId;
2447         density = option == 'd' ? temp : density;
2448     }
2449 
2450     if (result != OHOS::ERR_OK) {
2451         resultReceiver_.append(HELP_MSG_GET_ICON);
2452     } else {
2453         std::string results = "";
2454         results = bundleMgrProxy_->GetIconById(bundleName, moduleName, iconId, density, userId);
2455         if (results.empty()) {
2456             resultReceiver_.append(STRING_GET_ICON_NG);
2457             return result;
2458         }
2459         resultReceiver_.append(results);
2460     }
2461     return result;
2462 }
2463 
CheckAddInstallRuleCorrectOption(int option,const std::string & commandName,std::vector<std::string> & appIds,int & controlRuleType,int & userId,int & euid)2464 ErrCode BundleTestTool::CheckAddInstallRuleCorrectOption(int option, const std::string &commandName,
2465     std::vector<std::string> &appIds, int &controlRuleType, int &userId, int &euid)
2466 {
2467     bool ret = true;
2468     switch (option) {
2469         case 'h': {
2470             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2471             return OHOS::ERR_INVALID_VALUE;
2472         }
2473         case 'a': {
2474             std::string arrayAppId = optarg;
2475             std::stringstream array(arrayAppId);
2476             std::string object;
2477             while (getline(array, object, ',')) {
2478                 appIds.emplace_back(object);
2479             }
2480             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
2481             break;
2482         }
2483         case 'e': {
2484             StringToInt(optarg, commandName, euid, ret);
2485             break;
2486         }
2487         case 't': {
2488             StringToInt(optarg, commandName, controlRuleType, ret);
2489             break;
2490         }
2491         case 'u': {
2492             StringToInt(optarg, commandName, userId, ret);
2493             break;
2494         }
2495         default: {
2496             std::string unknownOption = "";
2497             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2498             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2499             resultReceiver_.append(unknownOptionMsg);
2500             return OHOS::ERR_INVALID_VALUE;
2501         }
2502     }
2503     return OHOS::ERR_OK;
2504 }
2505 
2506 // bundle_test_tool addAppInstallRule -a test1,test2 -t 1 -u 101 -e 3057
RunAsAddInstallRuleCommand()2507 ErrCode BundleTestTool::RunAsAddInstallRuleCommand()
2508 {
2509     ErrCode result = OHOS::ERR_OK;
2510     int counter = 0;
2511     std::string commandName = "addAppInstallRule";
2512     std::vector<std::string> appIds;
2513     int euid = 3057;
2514     int userId = 100;
2515     int ruleType = 0;
2516     APP_LOGD("RunAsAddInstallRuleCommand is start");
2517     while (true) {
2518         counter++;
2519         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2520         if (optind < 0 || optind > argc_) {
2521             return OHOS::ERR_INVALID_VALUE;
2522         }
2523         if (option == -1) {
2524             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2525                 resultReceiver_.append(HELP_MSG_NO_ADD_INSTALL_RULE_OPTION);
2526                 return OHOS::ERR_INVALID_VALUE;
2527             }
2528             break;
2529         }
2530         result = CheckAddInstallRuleCorrectOption(option, commandName, appIds, ruleType, userId, euid);
2531         if (result != OHOS::ERR_OK) {
2532             resultReceiver_.append(HELP_MSG_ADD_INSTALL_RULE);
2533             return OHOS::ERR_INVALID_VALUE;
2534         }
2535     }
2536     seteuid(euid);
2537     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2538     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2539     if (!appControlProxy) {
2540         APP_LOGE("fail to get app control proxy.");
2541         return OHOS::ERR_INVALID_VALUE;
2542     }
2543     std::string appIdParam = "";
2544     for (auto param : appIds) {
2545         appIdParam = appIdParam.append(param) + ";";
2546     }
2547     APP_LOGI("appIds: %{public}s, controlRuleType: %{public}d, userId: %{public}d",
2548         appIdParam.c_str(), ruleType, userId);
2549     int32_t res = appControlProxy->AddAppInstallControlRule(appIds, rule, userId);
2550     APP_LOGI("AddAppInstallControlRule return code: %{public}d", res);
2551     if (res != OHOS::ERR_OK) {
2552         resultReceiver_.append(STRING_ADD_RULE_NG);
2553         return res;
2554     }
2555     resultReceiver_.append(std::to_string(res) + "\n");
2556     return result;
2557 }
2558 
CheckGetInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)2559 ErrCode BundleTestTool::CheckGetInstallRuleCorrectOption(int option, const std::string &commandName,
2560     int &controlRuleType, int &userId, int &euid)
2561 {
2562     bool ret = true;
2563     switch (option) {
2564         case 'h': {
2565             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2566             return OHOS::ERR_INVALID_VALUE;
2567         }
2568         case 'e': {
2569             StringToInt(optarg, commandName, euid, ret);
2570             break;
2571         }
2572         case 't': {
2573             StringToInt(optarg, commandName, controlRuleType, ret);
2574             break;
2575         }
2576         case 'u': {
2577             StringToInt(optarg, commandName, userId, ret);
2578             break;
2579         }
2580         default: {
2581             std::string unknownOption = "";
2582             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2583             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2584             resultReceiver_.append(unknownOptionMsg);
2585             return OHOS::ERR_INVALID_VALUE;
2586         }
2587     }
2588     return OHOS::ERR_OK;
2589 }
2590 
2591 // bundle_test_tool getAppInstallRule -t 1 -u 101 -e 3057
RunAsGetInstallRuleCommand()2592 ErrCode BundleTestTool::RunAsGetInstallRuleCommand()
2593 {
2594     ErrCode result = OHOS::ERR_OK;
2595     int counter = 0;
2596     std::string commandName = "getAppInstallRule";
2597     int euid = 3057;
2598     int userId = 100;
2599     int ruleType = 0;
2600     APP_LOGD("RunAsGetInstallRuleCommand is start");
2601     while (true) {
2602         counter++;
2603         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2604         if (optind < 0 || optind > argc_) {
2605             return OHOS::ERR_INVALID_VALUE;
2606         }
2607         if (option == -1) {
2608             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2609                 resultReceiver_.append(HELP_MSG_NO_GET_INSTALL_RULE_OPTION);
2610                 return OHOS::ERR_INVALID_VALUE;
2611             }
2612             break;
2613         }
2614         result = CheckGetInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
2615         if (result != OHOS::ERR_OK) {
2616             resultReceiver_.append(HELP_MSG_GET_INSTALL_RULE);
2617             return OHOS::ERR_INVALID_VALUE;
2618         }
2619     }
2620     seteuid(euid);
2621     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2622     if (!appControlProxy) {
2623         APP_LOGE("fail to get app control proxy.");
2624         return OHOS::ERR_INVALID_VALUE;
2625     }
2626     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
2627     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2628     std::vector<std::string> appIds;
2629     int32_t res = appControlProxy->GetAppInstallControlRule(rule, userId, appIds);
2630     APP_LOGI("GetAppInstallControlRule return code: %{public}d", res);
2631     if (res != OHOS::ERR_OK) {
2632         resultReceiver_.append(STRING_GET_RULE_NG);
2633         return res;
2634     }
2635     std::string appIdParam = "";
2636     for (auto param : appIds) {
2637         appIdParam = appIdParam.append(param) + "; ";
2638     }
2639     resultReceiver_.append("appId : " + appIdParam + "\n");
2640     return result;
2641 }
2642 
CheckDeleteInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,std::vector<std::string> & appIds,int & userId,int & euid)2643 ErrCode BundleTestTool::CheckDeleteInstallRuleCorrectOption(int option, const std::string &commandName,
2644     int &controlRuleType, std::vector<std::string> &appIds, int &userId, int &euid)
2645 {
2646     bool ret = true;
2647     switch (option) {
2648         case 'h': {
2649             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2650             return OHOS::ERR_INVALID_VALUE;
2651         }
2652         case 'a': {
2653             std::string arrayAppId = optarg;
2654             std::stringstream array(arrayAppId);
2655             std::string object;
2656             while (getline(array, object, ',')) {
2657                 appIds.emplace_back(object);
2658             }
2659             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
2660             break;
2661         }
2662         case 'e': {
2663             StringToInt(optarg, commandName, euid, ret);
2664             break;
2665         }
2666         case 't': {
2667             StringToInt(optarg, commandName, controlRuleType, ret);
2668             break;
2669         }
2670         case 'u': {
2671             StringToInt(optarg, commandName, userId, ret);
2672             break;
2673         }
2674         default: {
2675             std::string unknownOption = "";
2676             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2677             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2678             resultReceiver_.append(unknownOptionMsg);
2679             return OHOS::ERR_INVALID_VALUE;
2680         }
2681     }
2682     return OHOS::ERR_OK;
2683 }
2684 
2685 // bundle_test_tool deleteAppInstallRule -a test1 -t 1 -u 101 -e 3057
RunAsDeleteInstallRuleCommand()2686 ErrCode BundleTestTool::RunAsDeleteInstallRuleCommand()
2687 {
2688     ErrCode result = OHOS::ERR_OK;
2689     int counter = 0;
2690     int euid = 3057;
2691     std::string commandName = "deleteAppInstallRule";
2692     std::vector<std::string> appIds;
2693     int ruleType = 0;
2694     int userId = 100;
2695     APP_LOGD("RunAsDeleteInstallRuleCommand is start");
2696     while (true) {
2697         counter++;
2698         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2699         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2700         if (optind < 0 || optind > argc_) {
2701             return OHOS::ERR_INVALID_VALUE;
2702         }
2703         if (option == -1) {
2704             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2705                 resultReceiver_.append(HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION);
2706                 return OHOS::ERR_INVALID_VALUE;
2707             }
2708             break;
2709         }
2710         result = CheckDeleteInstallRuleCorrectOption(option, commandName, ruleType, appIds, userId, euid);
2711         if (result != OHOS::ERR_OK) {
2712             resultReceiver_.append(HELP_MSG_DELETE_INSTALL_RULE);
2713             return OHOS::ERR_INVALID_VALUE;
2714         }
2715     }
2716     seteuid(euid);
2717     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2718     if (!appControlProxy) {
2719         APP_LOGE("fail to get app control proxy.");
2720         return OHOS::ERR_INVALID_VALUE;
2721     }
2722     std::string appIdParam = "";
2723     for (auto param : appIds) {
2724         appIdParam = appIdParam.append(param) + ";";
2725     }
2726     APP_LOGI("appIds: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2727     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2728     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, appIds, userId);
2729     APP_LOGI("DeleteAppInstallControlRule return code: %{public}d", res);
2730     if (res != OHOS::ERR_OK) {
2731         resultReceiver_.append(STRING_DELETE_RULE_NG);
2732         return res;
2733     }
2734     resultReceiver_.append(std::to_string(res) + "\n");
2735     return result;
2736 }
2737 
CheckCleanInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)2738 ErrCode BundleTestTool::CheckCleanInstallRuleCorrectOption(
2739     int option, const std::string &commandName, int &controlRuleType, int &userId, int &euid)
2740 {
2741     bool ret = true;
2742     switch (option) {
2743         case 'h': {
2744             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2745             return OHOS::ERR_INVALID_VALUE;
2746         }
2747         case 'e': {
2748             StringToInt(optarg, commandName, euid, ret);
2749             break;
2750         }
2751         case 't': {
2752             StringToInt(optarg, commandName, controlRuleType, ret);
2753             break;
2754         }
2755         case 'u': {
2756             StringToInt(optarg, commandName, userId, ret);
2757             break;
2758         }
2759         default: {
2760             std::string unknownOption = "";
2761             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2762             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2763             resultReceiver_.append(unknownOptionMsg);
2764             return OHOS::ERR_INVALID_VALUE;
2765         }
2766     }
2767     return OHOS::ERR_OK;
2768 }
2769 
2770 // bundle_test_tool cleanAppInstallRule -t 1 -u 101 -e 3057
RunAsCleanInstallRuleCommand()2771 ErrCode BundleTestTool::RunAsCleanInstallRuleCommand()
2772 {
2773     ErrCode result = OHOS::ERR_OK;
2774     int counter = 0;
2775     int euid = 3057;
2776     std::string commandName = "cleanAppInstallRule";
2777     int userId = 100;
2778     int ruleType = 0;
2779     APP_LOGD("RunAsCleanInstallRuleCommand is start");
2780     while (true) {
2781         counter++;
2782         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2783         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2784         if (optind < 0 || optind > argc_) {
2785             return OHOS::ERR_INVALID_VALUE;
2786         }
2787         if (option == -1) {
2788             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2789                 APP_LOGD("bundle_test_tool getRule with no option.");
2790                 resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
2791                 return OHOS::ERR_INVALID_VALUE;
2792             }
2793             break;
2794         }
2795         result = CheckCleanInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
2796         if (result != OHOS::ERR_OK) {
2797             resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
2798             return OHOS::ERR_INVALID_VALUE;
2799         }
2800     }
2801     seteuid(euid);
2802     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2803     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2804     if (!appControlProxy) {
2805         APP_LOGE("fail to get app control proxy.");
2806         return OHOS::ERR_INVALID_VALUE;
2807     }
2808     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
2809     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, userId);
2810     APP_LOGI("DeleteAppInstallControlRule clean return code: %{public}d", res);
2811     if (res != OHOS::ERR_OK) {
2812         resultReceiver_.append(STRING_DELETE_RULE_NG);
2813         return res;
2814     }
2815     resultReceiver_.append(std::to_string(res) + "\n");
2816     return result;
2817 }
2818 
CheckAppRunningRuleCorrectOption(int option,const std::string & commandName,std::vector<AppRunningControlRule> & controlRule,int & userId,int & euid)2819 ErrCode BundleTestTool::CheckAppRunningRuleCorrectOption(int option, const std::string &commandName,
2820     std::vector<AppRunningControlRule> &controlRule, int &userId, int &euid)
2821 {
2822     bool ret = true;
2823     switch (option) {
2824         case 'h': {
2825             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2826             return OHOS::ERR_INVALID_VALUE;
2827         }
2828         case 'c': {
2829             std::string arrayJsonRule = optarg;
2830             std::stringstream array(arrayJsonRule);
2831             std::string object;
2832             while (getline(array, object, ';')) {
2833                 size_t pos1 = object.find("appId");
2834                 size_t pos2 = object.find("controlMessage");
2835                 size_t pos3 = object.find(":", pos2);
2836                 if ((pos1 == std::string::npos) || (pos2 == std::string::npos)) {
2837                     return OHOS::ERR_INVALID_VALUE;
2838                 }
2839                 std::string appId = object.substr(pos1+6, pos2-pos1-7);
2840                 std::string controlMessage = object.substr(pos3+1);
2841                 AppRunningControlRule rule;
2842                 rule.appId = appId;
2843                 rule.controlMessage = controlMessage;
2844                 controlRule.emplace_back(rule);
2845             }
2846             break;
2847         }
2848         case 'e': {
2849             StringToInt(optarg, commandName, euid, ret);
2850             break;
2851         }
2852         case 'u': {
2853             StringToInt(optarg, commandName, userId, ret);
2854             break;
2855         }
2856         default: {
2857             std::string unknownOption = "";
2858             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2859             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2860             resultReceiver_.append(unknownOptionMsg);
2861             return OHOS::ERR_INVALID_VALUE;
2862         }
2863     }
2864     return OHOS::ERR_OK;
2865 }
2866 
2867 // bundle_test_tool addAppRunningRule -c appId:id1,controlMessage:msg1;appId:id2,controlMessage:msg2
2868 // -u 101 -e 3057
RunAsAddAppRunningRuleCommand()2869 ErrCode BundleTestTool::RunAsAddAppRunningRuleCommand()
2870 {
2871     ErrCode result = OHOS::ERR_OK;
2872     int counter = 0;
2873     int euid = 3057;
2874     std::string commandName = "addAppRunningRule";
2875     int userId = 100;
2876     std::vector<AppRunningControlRule> controlRule;
2877     APP_LOGD("RunAsAddAppRunningRuleCommand is start");
2878     while (true) {
2879         counter++;
2880         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2881         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2882         if (optind < 0 || optind > argc_) {
2883             return OHOS::ERR_INVALID_VALUE;
2884         }
2885         if (option == -1) {
2886             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2887                 APP_LOGD("bundle_test_tool getRule with no option.");
2888                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
2889                 return OHOS::ERR_INVALID_VALUE;
2890             }
2891             break;
2892         }
2893         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
2894         if (result != OHOS::ERR_OK) {
2895             resultReceiver_.append(HELP_MSG_ADD_APP_RUNNING_RULE);
2896             return OHOS::ERR_INVALID_VALUE;
2897         }
2898     }
2899     seteuid(euid);
2900     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2901     if (!appControlProxy) {
2902         APP_LOGE("fail to get app control proxy.");
2903         return OHOS::ERR_INVALID_VALUE;
2904     }
2905     std::string appIdParam = "";
2906     for (auto param : controlRule) {
2907         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
2908     }
2909     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2910     int32_t res = appControlProxy->AddAppRunningControlRule(controlRule, userId);
2911     if (res != OHOS::ERR_OK) {
2912         resultReceiver_.append(STRING_ADD_RULE_NG);
2913         return res;
2914     }
2915     resultReceiver_.append(std::to_string(res) + "\n");
2916     return result;
2917 }
2918 
2919 // bundle_test_tool deleteAppRunningRule -c appId:101,controlMessage:msg1 -u 101 -e 3057
RunAsDeleteAppRunningRuleCommand()2920 ErrCode BundleTestTool::RunAsDeleteAppRunningRuleCommand()
2921 {
2922     ErrCode result = OHOS::ERR_OK;
2923     int counter = 0;
2924     int euid = 3057;
2925     std::string commandName = "addAppRunningRule";
2926     int userId = 100;
2927     std::vector<AppRunningControlRule> controlRule;
2928     APP_LOGD("RunAsDeleteAppRunningRuleCommand is start");
2929     while (true) {
2930         counter++;
2931         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2932         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2933         if (optind < 0 || optind > argc_) {
2934             return OHOS::ERR_INVALID_VALUE;
2935         }
2936         if (option == -1) {
2937             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2938                 APP_LOGD("bundle_test_tool getRule with no option.");
2939                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
2940                 return OHOS::ERR_INVALID_VALUE;
2941             }
2942             break;
2943         }
2944         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
2945         if (result != OHOS::ERR_OK) {
2946             resultReceiver_.append(HELP_MSG_DELETE_APP_RUNNING_RULE);
2947             return OHOS::ERR_INVALID_VALUE;
2948         }
2949     }
2950     seteuid(euid);
2951     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2952     if (!appControlProxy) {
2953         APP_LOGE("fail to get app control proxy.");
2954         return OHOS::ERR_INVALID_VALUE;
2955     }
2956     std::string appIdParam = "";
2957     for (auto param : controlRule) {
2958         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
2959     }
2960     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2961     int32_t res = appControlProxy->DeleteAppRunningControlRule(controlRule, userId);
2962     if (res != OHOS::ERR_OK) {
2963         resultReceiver_.append(STRING_DELETE_RULE_NG);
2964         return res;
2965     }
2966     resultReceiver_.append(std::to_string(res) + "\n");
2967     return result;
2968 }
2969 
CheckCleanAppRunningRuleCorrectOption(int option,const std::string & commandName,int & userId,int & euid)2970 ErrCode BundleTestTool::CheckCleanAppRunningRuleCorrectOption(
2971     int option, const std::string &commandName, int &userId, int &euid)
2972 {
2973     bool ret = true;
2974     switch (option) {
2975         case 'h': {
2976             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2977             return OHOS::ERR_INVALID_VALUE;
2978         }
2979         case 'e': {
2980             StringToInt(optarg, commandName, euid, ret);
2981             break;
2982         }
2983         case 'u': {
2984             StringToInt(optarg, commandName, userId, ret);
2985             break;
2986         }
2987         default: {
2988             std::string unknownOption = "";
2989             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2990             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2991             resultReceiver_.append(unknownOptionMsg);
2992             return OHOS::ERR_INVALID_VALUE;
2993         }
2994     }
2995     return OHOS::ERR_OK;
2996 }
2997 
2998 // bundle_test_tool cleanAppRunningRule -u 101 -e 3057
RunAsCleanAppRunningRuleCommand()2999 ErrCode BundleTestTool::RunAsCleanAppRunningRuleCommand()
3000 {
3001     ErrCode result = OHOS::ERR_OK;
3002     int counter = 0;
3003     int euid = 3057;
3004     std::string commandName = "addAppRunningRule";
3005     int userId = 100;
3006     APP_LOGD("RunAsCleanAppRunningRuleCommand is start");
3007     while (true) {
3008         counter++;
3009         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
3010         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3011         if (optind < 0 || optind > argc_) {
3012             return OHOS::ERR_INVALID_VALUE;
3013         }
3014         if (option == -1) {
3015             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3016                 APP_LOGD("bundle_test_tool getRule with no option.");
3017                 resultReceiver_.append(HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION);
3018                 return OHOS::ERR_INVALID_VALUE;
3019             }
3020             break;
3021         }
3022         result = CheckCleanAppRunningRuleCorrectOption(option, commandName, userId, euid);
3023         if (result != OHOS::ERR_OK) {
3024             resultReceiver_.append(HELP_MSG_CLEAN_APP_RUNNING_RULE);
3025             return OHOS::ERR_INVALID_VALUE;
3026         }
3027     }
3028     seteuid(euid);
3029     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
3030     if (!appControlProxy) {
3031         APP_LOGE("fail to get app control proxy.");
3032         return OHOS::ERR_INVALID_VALUE;
3033     }
3034     APP_LOGI("userId: %{public}d", userId);
3035     int32_t res = appControlProxy->DeleteAppRunningControlRule(userId);
3036     if (res != OHOS::ERR_OK) {
3037         resultReceiver_.append(STRING_DELETE_RULE_NG);
3038         return res;
3039     }
3040     resultReceiver_.append(std::to_string(res) + "\n");
3041     return result;
3042 }
3043 
CheckGetAppRunningRuleCorrectOption(int option,const std::string & commandName,int32_t & userId,int & euid)3044 ErrCode BundleTestTool::CheckGetAppRunningRuleCorrectOption(int option, const std::string &commandName,
3045     int32_t &userId, int &euid)
3046 {
3047     bool ret = true;
3048     switch (option) {
3049         case 'h': {
3050             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
3051             return OHOS::ERR_INVALID_VALUE;
3052         }
3053         case 'e': {
3054             StringToInt(optarg, commandName, euid, ret);
3055             break;
3056         }
3057         case 'u': {
3058             StringToInt(optarg, commandName, userId, ret);
3059             break;
3060         }
3061         default: {
3062             std::string unknownOption = "";
3063             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3064             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
3065             resultReceiver_.append(unknownOptionMsg);
3066             return OHOS::ERR_INVALID_VALUE;
3067         }
3068     }
3069     return OHOS::ERR_OK ;
3070 }
3071 
3072 // bundle_test_tool getAppRunningControlRule -u 101 -e 3057
RunAsGetAppRunningControlRuleCommand()3073 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleCommand()
3074 {
3075     ErrCode result = OHOS::ERR_OK;
3076     int counter = 0;
3077     int euid = 3057;
3078     std::string commandName = "addAppRunningRule";
3079     int userId = 100;
3080     APP_LOGD("RunAsGetAppRunningControlRuleCommand is start");
3081     while (true) {
3082         counter++;
3083         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
3084         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3085         if (optind < 0 || optind > argc_) {
3086             return OHOS::ERR_INVALID_VALUE;
3087         }
3088         if (option == -1) {
3089             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3090                 APP_LOGD("bundle_test_tool getRule with no option.");
3091                 resultReceiver_.append(HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION);
3092                 return OHOS::ERR_INVALID_VALUE;
3093             }
3094             break;
3095         }
3096         result = CheckGetAppRunningRuleCorrectOption(option, commandName, userId, euid);
3097         if (result != OHOS::ERR_OK) {
3098             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RULE);
3099             return OHOS::ERR_INVALID_VALUE;
3100         }
3101     }
3102     seteuid(euid);
3103     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
3104     if (!appControlProxy) {
3105         APP_LOGE("fail to get app control proxy.");
3106         return OHOS::ERR_INVALID_VALUE;
3107     }
3108     APP_LOGI("userId: %{public}d", userId);
3109     std::vector<std::string> appIds;
3110     int32_t res = appControlProxy->GetAppRunningControlRule(userId, appIds);
3111     if (res != OHOS::ERR_OK) {
3112         resultReceiver_.append(STRING_GET_RULE_NG);
3113         return res;
3114     }
3115     std::string appIdParam = "";
3116     for (auto param : appIds) {
3117         appIdParam = appIdParam.append(param) + "; ";
3118     }
3119     resultReceiver_.append("appId : " + appIdParam + "\n");
3120     return result;
3121 }
3122 
CheckGetAppRunningRuleResultCorrectOption(int option,const std::string & commandName,std::string & bundleName,int32_t & userId,int & euid)3123 ErrCode BundleTestTool::CheckGetAppRunningRuleResultCorrectOption(int option, const std::string &commandName,
3124     std::string &bundleName, int32_t &userId, int &euid)
3125 {
3126     bool ret = true;
3127     switch (option) {
3128         case 'h': {
3129             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
3130             return OHOS::ERR_INVALID_VALUE;
3131         }
3132         case 'e': {
3133             StringToInt(optarg, commandName, euid, ret);
3134             break;
3135         }
3136         case 'n': {
3137             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
3138             bundleName = optarg;
3139             break;
3140         }
3141         case 'u': {
3142             StringToInt(optarg, commandName, userId, ret);
3143             break;
3144         }
3145         default: {
3146             std::string unknownOption = "";
3147             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3148             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
3149             resultReceiver_.append(unknownOptionMsg);
3150             return OHOS::ERR_INVALID_VALUE;
3151         }
3152     }
3153     return OHOS::ERR_OK;
3154 }
3155 
3156 // bundle_test_tool getAppRunningControlRuleResult -n com.ohos.example -e 3057
RunAsGetAppRunningControlRuleResultCommand()3157 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleResultCommand()
3158 {
3159     ErrCode result = OHOS::ERR_OK;
3160     int counter = 0;
3161     int euid = 3057;
3162     std::string commandName = "addAppRunningRule";
3163     int userId = 100;
3164     std::string bundleName;
3165     APP_LOGD("RunAsGetAppRunningControlRuleResultCommand is start");
3166     while (true) {
3167         counter++;
3168         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
3169         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3170         if (optind < 0 || optind > argc_) {
3171             return OHOS::ERR_INVALID_VALUE;
3172         }
3173         if (option == -1) {
3174             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3175                 APP_LOGD("bundle_test_tool getRule with no option.");
3176                 resultReceiver_.append(HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION);
3177                 return OHOS::ERR_INVALID_VALUE;
3178             }
3179             break;
3180         }
3181         result = CheckGetAppRunningRuleResultCorrectOption(option, commandName, bundleName, userId, euid);
3182         if (result != OHOS::ERR_OK) {
3183             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RESULT_RULE);
3184             return OHOS::ERR_INVALID_VALUE;
3185         }
3186     }
3187     seteuid(euid);
3188     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
3189     if (!appControlProxy) {
3190         APP_LOGE("fail to get app control proxy.");
3191         return OHOS::ERR_INVALID_VALUE;
3192     }
3193     AppRunningControlRuleResult ruleResult;
3194     APP_LOGI("bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
3195     int32_t res = appControlProxy->GetAppRunningControlRule(bundleName, userId, ruleResult);
3196     if (res != OHOS::ERR_OK) {
3197         APP_LOGI("GetAppRunningControlRule result: %{public}d", res);
3198         resultReceiver_.append("message:" + ruleResult.controlMessage + " bundle:notFind" + "\n");
3199         return res;
3200     }
3201     resultReceiver_.append("message:" + ruleResult.controlMessage + "\n");
3202     if (ruleResult.controlWant != nullptr) {
3203         resultReceiver_.append("controlWant:" + ruleResult.controlWant->ToString() + "\n");
3204     } else {
3205         resultReceiver_.append("controlWant: nullptr \n");
3206     }
3207     return result;
3208 }
3209 
CheckCleanBundleCacheFilesAutomaticOption(int option,const std::string & commandName,uint64_t & cacheSize)3210 ErrCode BundleTestTool::CheckCleanBundleCacheFilesAutomaticOption(
3211     int option, const std::string &commandName, uint64_t &cacheSize)
3212 {
3213     bool ret = true;
3214     switch (option) {
3215         case 'h': {
3216             APP_LOGI("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
3217             return OHOS::ERR_INVALID_VALUE;
3218         }
3219         case 's': {
3220             APP_LOGI("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
3221             StringToUnsignedLongLong(optarg, commandName, cacheSize, ret);
3222             break;
3223         }
3224         default: {
3225             std::string unknownOption = "";
3226             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3227             APP_LOGE("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
3228             resultReceiver_.append(unknownOptionMsg);
3229             return OHOS::ERR_INVALID_VALUE;
3230         }
3231     }
3232     return OHOS::ERR_OK;
3233 }
3234 
RunAsCleanBundleCacheFilesAutomaticCommand()3235 ErrCode BundleTestTool::RunAsCleanBundleCacheFilesAutomaticCommand()
3236 {
3237     ErrCode result = OHOS::ERR_OK;
3238     int counter = 0;
3239     std::string commandName = "cleanBundleCacheFilesAutomatic";
3240     uint64_t cacheSize;
3241     APP_LOGI("RunAsCleanBundleCacheFilesAutomaticCommand is start");
3242     while (true) {
3243         counter++;
3244         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_AUTO_CLEAN_CACHE.c_str(),
3245             LONG_OPTIONS_AUTO_CLEAN_CACHE, nullptr);
3246         APP_LOGI("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3247         if (optind < 0 || optind > argc_) {
3248             return OHOS::ERR_INVALID_VALUE;
3249         }
3250         if (option == -1) {
3251             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3252                 APP_LOGE("bundle_test_tool getRule with no option.");
3253                 resultReceiver_.append(HELP_MSG_NO_AUTO_CLEAN_CACHE_OPTION);
3254                 return OHOS::ERR_INVALID_VALUE;
3255             }
3256             break;
3257         }
3258         result = CheckCleanBundleCacheFilesAutomaticOption(option, commandName, cacheSize);
3259         if (result != OHOS::ERR_OK) {
3260             resultReceiver_.append(HELP_MSG_AUTO_CLEAN_CACHE_RULE);
3261             return OHOS::ERR_INVALID_VALUE;
3262         }
3263     }
3264 
3265     ErrCode res = bundleMgrProxy_->CleanBundleCacheFilesAutomatic(cacheSize);
3266     if (res == ERR_OK) {
3267         resultReceiver_.append("clean fixed size cache successfully\n");
3268     } else {
3269         resultReceiver_.append("clean fixed size cache failed, errCode is "+ std::to_string(res) + "\n");
3270         APP_LOGE("CleanBundleCacheFilesAutomatic failed, result: %{public}d", res);
3271         return res;
3272     }
3273 
3274     return res;
3275 }
3276 
RunAsGetContinueBundleName()3277 ErrCode BundleTestTool::RunAsGetContinueBundleName()
3278 {
3279     APP_LOGD("RunAsGetContinueBundleName start");
3280     std::string bundleName;
3281     int32_t userId = Constants::UNSPECIFIED_USERID;
3282     int32_t appIndex;
3283     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3284     if (result != OHOS::ERR_OK) {
3285         resultReceiver_.append("RunAsGetContinueBundleName erro!!");
3286     } else {
3287         if (userId == Constants::UNSPECIFIED_USERID) {
3288             int32_t mockUid = 20010099;
3289             // Mock the current tool uid, the current default user must be executed under 100.
3290             int setResult = setuid(mockUid);
3291             APP_LOGD("Set uid result: %{public}d", setResult);
3292         }
3293 
3294         std::string msg;
3295         result = GetContinueBundleName(bundleName, userId, msg);
3296         APP_LOGD("Get continue bundle result %{public}d", result);
3297         if (result == OHOS::ERR_OK) {
3298             resultReceiver_.append(msg);
3299             return ERR_OK;
3300         } else {
3301             APP_LOGE("Get continue bundle name error: %{public}d", result);
3302             std::string err("Get continue bundle name error!");
3303             resultReceiver_.append(err);
3304         }
3305     }
3306     return OHOS::ERR_INVALID_VALUE;
3307 }
3308 
GetContinueBundleName(const std::string & bundleName,int32_t userId,std::string & msg)3309 ErrCode BundleTestTool::GetContinueBundleName(const std::string &bundleName, int32_t userId, std::string& msg)
3310 {
3311     if (bundleMgrProxy_ == nullptr) {
3312         APP_LOGE("Bundle mgr proxy is nullptr");
3313         return OHOS::ERR_INVALID_VALUE;
3314     }
3315     std::vector<std::string> continueBundleName;
3316     auto ret = bundleMgrProxy_->GetContinueBundleNames(bundleName, continueBundleName, userId);
3317     APP_LOGD("Get continue bundle names result: %{public}d", ret);
3318     if (ret == OHOS::ERR_OK) {
3319         msg = "continueBundleNameList:\n{\n";
3320         for (const auto &name : continueBundleName) {
3321             msg +="     ";
3322             msg += name;
3323             msg += "\n";
3324         }
3325         msg += "}\n";
3326         return ERR_OK;
3327     }
3328     return ret;
3329 }
3330 
RunAsDeployQuickFix()3331 ErrCode BundleTestTool::RunAsDeployQuickFix()
3332 {
3333     int32_t result = OHOS::ERR_OK;
3334     int32_t counter = 0;
3335     int32_t index = 0;
3336     std::vector<std::string> quickFixPaths;
3337     int32_t isDebug = 0;
3338     while (true) {
3339         counter++;
3340         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3341         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3342         if (optind < 0 || optind > argc_) {
3343             return OHOS::ERR_INVALID_VALUE;
3344         }
3345 
3346         if (option == -1 || option == '?') {
3347             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3348                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3349                 result = OHOS::ERR_INVALID_VALUE;
3350                 break;
3351             }
3352             if ((optopt == 'p') || (optopt == 'd')) {
3353                 // 'bm deployQuickFix --patch-path' with no argument
3354                 // 'bm deployQuickFix -d' with no argument
3355                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3356                 result = OHOS::ERR_INVALID_VALUE;
3357                 break;
3358             }
3359             break;
3360         }
3361 
3362         if (option == 'p') {
3363             APP_LOGD("'bm deployQuickFix -p %{public}s'", argv_[optind - 1]);
3364             quickFixPaths.emplace_back(optarg);
3365             index = optind;
3366             continue;
3367         }
3368         if ((option == 'd') && OHOS::StrToInt(optarg, isDebug)) {
3369             APP_LOGD("'bm deployQuickFix -d %{public}s'", argv_[optind - 1]);
3370             continue;
3371         }
3372 
3373         result = OHOS::ERR_INVALID_VALUE;
3374         break;
3375     }
3376 
3377     if (result != OHOS::ERR_OK || GetQuickFixPath(index, quickFixPaths) != OHOS::ERR_OK) {
3378         resultReceiver_.append(HELP_MSG_DEPLOY_QUICK_FIX);
3379         return result;
3380     }
3381 
3382     std::shared_ptr<QuickFixResult> deployRes = nullptr;
3383     result = DeployQuickFix(quickFixPaths, deployRes, isDebug != 0);
3384     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DEPLOY_QUICK_FIX_OK : STRING_DEPLOY_QUICK_FIX_NG;
3385     resultReceiver_ += GetResMsg(result, deployRes);
3386 
3387     return result;
3388 }
3389 
GetQuickFixPath(int32_t index,std::vector<std::string> & quickFixPaths) const3390 ErrCode BundleTestTool::GetQuickFixPath(int32_t index, std::vector<std::string>& quickFixPaths) const
3391 {
3392     APP_LOGI("GetQuickFixPath start");
3393     for (; index < argc_ && index >= INDEX_OFFSET; ++index) {
3394         if (argList_[index - INDEX_OFFSET] == "-p" || argList_[index - INDEX_OFFSET] == "--patch-path") {
3395             break;
3396         }
3397 
3398         std::string innerPath = argList_[index - INDEX_OFFSET];
3399         if (innerPath.empty() || innerPath == "-p" || innerPath == "--patch-path") {
3400             quickFixPaths.clear();
3401             return OHOS::ERR_INVALID_VALUE;
3402         }
3403         APP_LOGD("GetQuickFixPath is %{public}s'", innerPath.c_str());
3404         quickFixPaths.emplace_back(innerPath);
3405     }
3406     return OHOS::ERR_OK;
3407 }
3408 
RunAsSwitchQuickFix()3409 ErrCode BundleTestTool::RunAsSwitchQuickFix()
3410 {
3411     int32_t result = OHOS::ERR_OK;
3412     int32_t counter = 0;
3413     int32_t enable = -1;
3414     std::string bundleName;
3415     while (true) {
3416         counter++;
3417         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3418         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3419         if (optind < 0 || optind > argc_) {
3420             return OHOS::ERR_INVALID_VALUE;
3421         }
3422 
3423         if (option == -1 || option == '?') {
3424             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3425                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3426                 result = OHOS::ERR_INVALID_VALUE;
3427                 break;
3428             }
3429             if (optopt == 'n' || optopt == 'e') {
3430                 // 'bm switchQuickFix -n -e' with no argument
3431                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3432                 result = OHOS::ERR_INVALID_VALUE;
3433                 break;
3434             }
3435             break;
3436         }
3437 
3438         if (option == 'n') {
3439             APP_LOGD("'bm switchQuickFix -n %{public}s'", argv_[optind - 1]);
3440             bundleName = optarg;
3441             continue;
3442         }
3443         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
3444             APP_LOGD("'bm switchQuickFix -e %{public}s'", argv_[optind - 1]);
3445             continue;
3446         }
3447         result = OHOS::ERR_INVALID_VALUE;
3448         break;
3449     }
3450 
3451     if ((result != OHOS::ERR_OK) || (enable < 0) || (enable > 1)) {
3452         resultReceiver_.append(HELP_MSG_SWITCH_QUICK_FIX);
3453         return result;
3454     }
3455     std::shared_ptr<QuickFixResult> switchRes = nullptr;
3456     result = SwitchQuickFix(bundleName, enable, switchRes);
3457     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_SWITCH_QUICK_FIX_OK : STRING_SWITCH_QUICK_FIX_NG;
3458     resultReceiver_ += GetResMsg(result, switchRes);
3459 
3460     return result;
3461 }
3462 
RunAsDeleteQuickFix()3463 ErrCode BundleTestTool::RunAsDeleteQuickFix()
3464 {
3465     int32_t result = OHOS::ERR_OK;
3466     int32_t counter = 0;
3467     std::string bundleName;
3468     while (true) {
3469         counter++;
3470         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3471         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3472         if (optind < 0 || optind > argc_) {
3473             return OHOS::ERR_INVALID_VALUE;
3474         }
3475 
3476         if (option == -1 || option == '?') {
3477             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3478                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3479                 result = OHOS::ERR_INVALID_VALUE;
3480                 break;
3481             }
3482             if (optopt == 'n') {
3483                 // 'bm deleteQuickFix -n' with no argument
3484                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3485                 result = OHOS::ERR_INVALID_VALUE;
3486                 break;
3487             }
3488             break;
3489         }
3490 
3491         if (option == 'n') {
3492             APP_LOGD("'bm deleteQuickFix -n %{public}s'", argv_[optind - 1]);
3493             bundleName = optarg;
3494             continue;
3495         }
3496         result = OHOS::ERR_INVALID_VALUE;
3497         break;
3498     }
3499 
3500     if (result != OHOS::ERR_OK) {
3501         resultReceiver_.append(HELP_MSG_DELETE_QUICK_FIX);
3502         return result;
3503     }
3504     std::shared_ptr<QuickFixResult> deleteRes = nullptr;
3505     result = DeleteQuickFix(bundleName, deleteRes);
3506     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DELETE_QUICK_FIX_OK : STRING_DELETE_QUICK_FIX_NG;
3507     resultReceiver_ += GetResMsg(result, deleteRes);
3508 
3509     return result;
3510 }
3511 
DeployQuickFix(const std::vector<std::string> & quickFixPaths,std::shared_ptr<QuickFixResult> & quickFixRes,bool isDebug)3512 ErrCode BundleTestTool::DeployQuickFix(const std::vector<std::string> &quickFixPaths,
3513     std::shared_ptr<QuickFixResult> &quickFixRes, bool isDebug)
3514 {
3515 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3516     std::set<std::string> realPathSet;
3517     for (const auto &quickFixPath : quickFixPaths) {
3518         std::string realPath;
3519         if (!PathToRealPath(quickFixPath, realPath)) {
3520             APP_LOGW("quickFixPath %{public}s is invalid", quickFixPath.c_str());
3521             continue;
3522         }
3523         APP_LOGD("realPath is %{public}s", realPath.c_str());
3524         realPathSet.insert(realPath);
3525     }
3526     std::vector<std::string> pathVec(realPathSet.begin(), realPathSet.end());
3527 
3528     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3529     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3530         APP_LOGE("callback or bundleMgrProxy is null");
3531         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3532     }
3533     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3534     if (recipient == nullptr) {
3535         APP_LOGE("recipient is null");
3536         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3537     }
3538     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3539     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3540     if (quickFixProxy == nullptr) {
3541         APP_LOGE("quickFixProxy is null");
3542         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3543     }
3544     std::vector<std::string> destFiles;
3545     auto res = quickFixProxy->CopyFiles(pathVec, destFiles);
3546     if (res != ERR_OK) {
3547         APP_LOGE("Copy files failed with %{public}d.", res);
3548         return res;
3549     }
3550     res = quickFixProxy->DeployQuickFix(destFiles, callback, isDebug);
3551     if (res != ERR_OK) {
3552         APP_LOGE("DeployQuickFix failed");
3553         return res;
3554     }
3555 
3556     return callback->GetResultCode(quickFixRes);
3557 #else
3558     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3559 #endif
3560 }
3561 
SwitchQuickFix(const std::string & bundleName,int32_t enable,std::shared_ptr<QuickFixResult> & quickFixRes)3562 ErrCode BundleTestTool::SwitchQuickFix(const std::string &bundleName, int32_t enable,
3563     std::shared_ptr<QuickFixResult> &quickFixRes)
3564 {
3565     APP_LOGD("SwitchQuickFix bundleName: %{public}s, enable: %{public}d", bundleName.c_str(), enable);
3566 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3567     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3568     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3569         APP_LOGE("callback or bundleMgrProxy is null");
3570         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3571     }
3572     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3573     if (recipient == nullptr) {
3574         APP_LOGE("recipient is null");
3575         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3576     }
3577     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3578     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3579     if (quickFixProxy == nullptr) {
3580         APP_LOGE("quickFixProxy is null");
3581         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3582     }
3583     bool enableFlag = (enable == 0) ? false : true;
3584     auto res = quickFixProxy->SwitchQuickFix(bundleName, enableFlag, callback);
3585     if (res != ERR_OK) {
3586         APP_LOGE("SwitchQuickFix failed");
3587         return res;
3588     }
3589     return callback->GetResultCode(quickFixRes);
3590 #else
3591     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3592 #endif
3593 }
3594 
DeleteQuickFix(const std::string & bundleName,std::shared_ptr<QuickFixResult> & quickFixRes)3595 ErrCode BundleTestTool::DeleteQuickFix(const std::string &bundleName,
3596     std::shared_ptr<QuickFixResult> &quickFixRes)
3597 {
3598     APP_LOGD("DeleteQuickFix bundleName: %{public}s", bundleName.c_str());
3599 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3600     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3601     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3602         APP_LOGE("callback or bundleMgrProxy is null");
3603         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3604     }
3605     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3606     if (recipient == nullptr) {
3607         APP_LOGE("recipient is null");
3608         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3609     }
3610     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3611     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3612     if (quickFixProxy == nullptr) {
3613         APP_LOGE("quickFixProxy is null");
3614         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3615     }
3616     auto res = quickFixProxy->DeleteQuickFix(bundleName, callback);
3617     if (res != ERR_OK) {
3618         APP_LOGE("DeleteQuickFix failed");
3619         return res;
3620     }
3621     return callback->GetResultCode(quickFixRes);
3622 #else
3623     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3624 #endif
3625 }
3626 
GetResMsg(int32_t code)3627 std::string BundleTestTool::GetResMsg(int32_t code)
3628 {
3629     std::unordered_map<int32_t, std::string> quickFixMsgMap;
3630     CreateQuickFixMsgMap(quickFixMsgMap);
3631     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
3632         return quickFixMsgMap.at(code);
3633     }
3634     return MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
3635 }
3636 
GetResMsg(int32_t code,const std::shared_ptr<QuickFixResult> & quickFixRes)3637 std::string BundleTestTool::GetResMsg(int32_t code, const std::shared_ptr<QuickFixResult> &quickFixRes)
3638 {
3639     std::string resMsg;
3640     std::unordered_map<int32_t, std::string> quickFixMsgMap;
3641     CreateQuickFixMsgMap(quickFixMsgMap);
3642     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
3643         resMsg += quickFixMsgMap.at(code);
3644     } else {
3645         resMsg += MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
3646     }
3647     if (quickFixRes != nullptr) {
3648         resMsg += quickFixRes->ToString() + "\n";
3649     }
3650     return resMsg;
3651 }
3652 
RunAsSetDebugMode()3653 ErrCode BundleTestTool::RunAsSetDebugMode()
3654 {
3655     int32_t result = OHOS::ERR_OK;
3656     int32_t counter = 0;
3657     int32_t enable = -1;
3658     while (true) {
3659         counter++;
3660         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_DEBUG_MODE.c_str(), LONG_OPTIONS_DEBUG_MODE, nullptr);
3661         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3662         if (optind < 0 || optind > argc_) {
3663             return OHOS::ERR_INVALID_VALUE;
3664         }
3665 
3666         if (option == -1 || option == '?') {
3667             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3668                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3669                 result = OHOS::ERR_INVALID_VALUE;
3670                 break;
3671             }
3672             if (optopt == 'e') {
3673                 // 'bundle_test_tool setDebugMode -e' with no argument
3674                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3675                 result = OHOS::ERR_INVALID_VALUE;
3676                 break;
3677             }
3678             break;
3679         }
3680 
3681         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
3682             APP_LOGD("'bundle_test_tool setDebugMode -e %{public}s'", argv_[optind - 1]);
3683             continue;
3684         }
3685         result = OHOS::ERR_INVALID_VALUE;
3686         break;
3687     }
3688 
3689     if (result != OHOS::ERR_OK) {
3690         resultReceiver_.append(HELP_MSG_SET_DEBUG_MODE);
3691         return result;
3692     }
3693     ErrCode setResult = SetDebugMode(enable);
3694     if (setResult == OHOS::ERR_OK) {
3695         resultReceiver_ = STRING_SET_DEBUG_MODE_OK;
3696     } else {
3697         resultReceiver_ = STRING_SET_DEBUG_MODE_NG + GetResMsg(setResult);
3698     }
3699     return setResult;
3700 }
3701 
SetDebugMode(int32_t debugMode)3702 ErrCode BundleTestTool::SetDebugMode(int32_t debugMode)
3703 {
3704     if (debugMode != 0 && debugMode != 1) {
3705         APP_LOGE("SetDebugMode param is invalid");
3706         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM;
3707     }
3708     bool enable = debugMode == 0 ? false : true;
3709     if (bundleMgrProxy_ == nullptr) {
3710         APP_LOGE("bundleMgrProxy_ is nullptr");
3711         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR;
3712     }
3713     return bundleMgrProxy_->SetDebugMode(enable);
3714 }
3715 
BundleNameAndUserIdCommonFunc(std::string & bundleName,int32_t & userId,int32_t & appIndex)3716 ErrCode BundleTestTool::BundleNameAndUserIdCommonFunc(std::string &bundleName, int32_t &userId, int32_t &appIndex)
3717 {
3718     int32_t result = OHOS::ERR_OK;
3719     int32_t counter = 0;
3720     userId = Constants::UNSPECIFIED_USERID;
3721     while (true) {
3722         counter++;
3723         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLE_STATS.c_str(),
3724             LONG_OPTIONS_GET_BUNDLE_STATS, nullptr);
3725         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3726         if (optind < 0 || optind > argc_) {
3727             return OHOS::ERR_INVALID_VALUE;
3728         }
3729         if (option == -1) {
3730             if (counter == 1) {
3731                 // When scanning the first argument
3732                 if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
3733                     resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3734                     result = OHOS::ERR_INVALID_VALUE;
3735                 }
3736             }
3737             break;
3738         }
3739 
3740         if (option == '?') {
3741             switch (optopt) {
3742                 case 'n': {
3743                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3744                     result = OHOS::ERR_INVALID_VALUE;
3745                     break;
3746                 }
3747                 case 'u': {
3748                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3749                     result = OHOS::ERR_INVALID_VALUE;
3750                     break;
3751                 }
3752                 case 'a': {
3753                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3754                     result = OHOS::ERR_INVALID_VALUE;
3755                     break;
3756                 }
3757                 default: {
3758                     std::string unknownOption = "";
3759                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3760                     resultReceiver_.append(unknownOptionMsg);
3761                     result = OHOS::ERR_INVALID_VALUE;
3762                     break;
3763                 }
3764             }
3765             break;
3766         }
3767 
3768         switch (option) {
3769             case 'h': {
3770                 result = OHOS::ERR_INVALID_VALUE;
3771                 break;
3772             }
3773             case 'n': {
3774                 bundleName = optarg;
3775                 break;
3776             }
3777             case 'u': {
3778                 if (!OHOS::StrToInt(optarg, userId) || userId < 0) {
3779                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3780                     return OHOS::ERR_INVALID_VALUE;
3781                 }
3782                 break;
3783             }
3784             case 'a': {
3785                 if (!OHOS::StrToInt(optarg, appIndex) || (appIndex < 0 || appIndex > INITIAL_SANDBOX_APP_INDEX)) {
3786                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3787                     return OHOS::ERR_INVALID_VALUE;
3788                 }
3789                 break;
3790             }
3791             default: {
3792                 result = OHOS::ERR_INVALID_VALUE;
3793                 break;
3794             }
3795         }
3796     }
3797 
3798     if (result == OHOS::ERR_OK) {
3799         if (resultReceiver_ == "" && bundleName.size() == 0) {
3800             resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION + "\n");
3801             result = OHOS::ERR_INVALID_VALUE;
3802         }
3803     }
3804     return result;
3805 }
3806 
RunAsGetBundleStats()3807 ErrCode BundleTestTool::RunAsGetBundleStats()
3808 {
3809     std::string bundleName;
3810     int32_t userId;
3811     int32_t appIndex = 0;
3812     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3813     if (result != OHOS::ERR_OK) {
3814         resultReceiver_.append(HELP_MSG_GET_BUNDLE_STATS);
3815     } else {
3816         std::string msg;
3817         bool ret = GetBundleStats(bundleName, userId, msg, appIndex);
3818         if (ret) {
3819             resultReceiver_ = STRING_GET_BUNDLE_STATS_OK + msg;
3820         } else {
3821             resultReceiver_ = STRING_GET_BUNDLE_STATS_NG + "\n";
3822         }
3823     }
3824 
3825     return result;
3826 }
3827 
GetBundleStats(const std::string & bundleName,int32_t userId,std::string & msg,int32_t appIndex)3828 bool BundleTestTool::GetBundleStats(const std::string &bundleName, int32_t userId,
3829     std::string& msg, int32_t appIndex)
3830 {
3831     if (bundleMgrProxy_ == nullptr) {
3832         APP_LOGE("bundleMgrProxy_ is nullptr");
3833         return false;
3834     }
3835     userId = BundleCommandCommon::GetCurrentUserId(userId);
3836     std::vector<std::int64_t> bundleStats;
3837     bool ret = bundleMgrProxy_->GetBundleStats(bundleName, userId, bundleStats, appIndex);
3838     if (ret) {
3839         for (size_t index = 0; index < bundleStats.size(); ++index) {
3840             msg += GET_BUNDLE_STATS_ARRAY[index] + std::to_string(bundleStats[index]) + "\n";
3841         }
3842     }
3843     return ret;
3844 }
3845 
RunAsGetAppProvisionInfo()3846 ErrCode BundleTestTool::RunAsGetAppProvisionInfo()
3847 {
3848     std::string bundleName;
3849     int32_t userId;
3850     int32_t appIndex = 0;
3851     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3852     if (result != OHOS::ERR_OK) {
3853         resultReceiver_.append(HELP_MSG_GET_APP_PROVISION_INFO);
3854     } else {
3855         std::string msg;
3856         result = GetAppProvisionInfo(bundleName, userId, msg);
3857         if (result == OHOS::ERR_OK) {
3858             resultReceiver_ = STRING_GET_APP_PROVISION_INFO_OK + msg;
3859         } else {
3860             resultReceiver_ = STRING_GET_APP_PROVISION_INFO_NG + "\n";
3861         }
3862     }
3863 
3864     return result;
3865 }
3866 
GetAppProvisionInfo(const std::string & bundleName,int32_t userId,std::string & msg)3867 ErrCode BundleTestTool::GetAppProvisionInfo(const std::string &bundleName,
3868     int32_t userId, std::string& msg)
3869 {
3870     if (bundleMgrProxy_ == nullptr) {
3871         APP_LOGE("bundleMgrProxy_ is nullptr");
3872         return OHOS::ERR_INVALID_VALUE;
3873     }
3874     userId = BundleCommandCommon::GetCurrentUserId(userId);
3875     AppProvisionInfo info;
3876     auto ret = bundleMgrProxy_->GetAppProvisionInfo(bundleName, userId, info);
3877     if (ret == ERR_OK) {
3878         msg = "{\n";
3879         msg += "    versionCode: " + std::to_string(info.versionCode) + "\n";
3880         msg += "    versionName: " + info.versionName+ "\n";
3881         msg += "    uuid: " + info.uuid + "\n";
3882         msg += "    type: " + info.type + "\n";
3883         msg += "    appDistributionType: " + info.appDistributionType + "\n";
3884         msg += "    developerId: " + info.developerId + "\n";
3885         msg += "    certificate: " + info.certificate + "\n";
3886         msg += "    apl: " + info.apl + "\n";
3887         msg += "    issuer: " + info.issuer + "\n";
3888         msg += "    validity: {\n";
3889         msg += "        notBefore: " + std::to_string(info.validity.notBefore) + "\n";
3890         msg += "        notAfter: " + std::to_string(info.validity.notAfter) + "\n";
3891         msg += "    }\n";
3892         msg += "    appServiceCapabilities: " + info.appServiceCapabilities + "\n";
3893         msg += "}\n";
3894     }
3895     return ret;
3896 }
3897 
RunAsGetDistributedBundleName()3898 ErrCode BundleTestTool::RunAsGetDistributedBundleName()
3899 {
3900     ErrCode result;
3901     std::string networkId;
3902     int32_t counter = 0;
3903     int32_t accessTokenId = 0;
3904     while (true) {
3905         counter++;
3906         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME.c_str(),
3907             LONG_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME, nullptr);
3908         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3909         if (optind < 0 || optind > argc_) {
3910             return OHOS::ERR_INVALID_VALUE;
3911         }
3912         if (option == -1) {
3913             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3914                 resultReceiver_.append(HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION);
3915                 return OHOS::ERR_INVALID_VALUE;
3916             }
3917             break;
3918         }
3919         result = CheckGetDistributedBundleNameCorrectOption(option, GET_DISTRIBUTED_BUNDLE_NAME_COMMAND_NAME,
3920             networkId, accessTokenId);
3921         if (result != OHOS::ERR_OK) {
3922             resultReceiver_.append(HELP_MSG_GET_DISTRIBUTED_BUNDLE_NAME);
3923             return OHOS::ERR_INVALID_VALUE;
3924         }
3925     }
3926     if (accessTokenId == 0 || networkId.size() == 0) {
3927         resultReceiver_.append(HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION);
3928         return OHOS::ERR_INVALID_VALUE;
3929     }
3930     std::string msg;
3931     result = GetDistributedBundleName(networkId, accessTokenId, msg);
3932     if (result == OHOS::ERR_OK) {
3933         resultReceiver_ = STRING_GET_DISTRIBUTED_BUNDLE_NAME_OK + msg;
3934     } else {
3935         resultReceiver_ = STRING_GET_DISTRIBUTED_BUNDLE_NAME_NG + "\n";
3936         APP_LOGE("RunAsGetDistributedBundleName fail result %{public}d.", result);
3937     }
3938     return result;
3939 }
3940 
CheckGetDistributedBundleNameCorrectOption(int32_t option,const std::string & commandName,std::string & networkId,int32_t & accessTokenId)3941 ErrCode BundleTestTool::CheckGetDistributedBundleNameCorrectOption(int32_t option, const std::string &commandName,
3942     std::string &networkId, int32_t &accessTokenId)
3943 {
3944     ErrCode result = OHOS::ERR_OK;
3945     switch (option) {
3946         case 'h': {
3947             result = OHOS::ERR_INVALID_VALUE;
3948             break;
3949         }
3950         case 'n': {
3951             networkId = optarg;
3952             if (networkId.size() == 0) {
3953                 return OHOS::ERR_INVALID_VALUE;
3954             }
3955             break;
3956         }
3957         case 'a': {
3958             if (!OHOS::StrToInt(optarg, accessTokenId) || accessTokenId < 0) {
3959                 return OHOS::ERR_INVALID_VALUE;
3960             }
3961             break;
3962         }
3963         default: {
3964             result = OHOS::ERR_INVALID_VALUE;
3965             break;
3966         }
3967     }
3968     return result;
3969 }
3970 
GetDistributedBundleName(const std::string & networkId,int32_t accessTokenId,std::string & msg)3971 ErrCode BundleTestTool::GetDistributedBundleName(const std::string &networkId,
3972     int32_t accessTokenId, std::string& msg)
3973 {
3974 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
3975     if (distributedBmsProxy_ == nullptr) {
3976         APP_LOGE("distributedBmsProxy_ is nullptr");
3977         return OHOS::ERR_INVALID_VALUE;
3978     }
3979     std::string bundleName;
3980     auto ret = distributedBmsProxy_->GetDistributedBundleName(networkId, accessTokenId, bundleName);
3981     if (ret == OHOS::NO_ERROR) {
3982         msg = "\n";
3983         if (bundleName.size() == 0) {
3984             msg += "no match found \n";
3985         } else {
3986             msg += bundleName + "\n";
3987         }
3988         msg += "\n";
3989     } else {
3990         APP_LOGE("distributedBmsProxy_ GetDistributedBundleName fail errcode %{public}d.", ret);
3991         return OHOS::ERR_INVALID_VALUE;
3992     }
3993     return OHOS::ERR_OK;
3994 #else
3995     return OHOS::ERR_INVALID_VALUE;
3996 #endif
3997 }
3998 
ParseEventCallbackOptions(bool & onlyUnregister,int32_t & uid)3999 bool BundleTestTool::ParseEventCallbackOptions(bool &onlyUnregister, int32_t &uid)
4000 {
4001     int32_t opt;
4002     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_BUNDLE_EVENT_CALLBACK.c_str(),
4003         LONG_OPTIONS_BUNDLE_EVENT_CALLBACK, nullptr)) != -1) {
4004         switch (opt) {
4005             case 'o': {
4006                 onlyUnregister = true;
4007                 break;
4008             }
4009             case 'u': {
4010                 if (!OHOS::StrToInt(optarg, uid)) {
4011                     std::string msg = "invalid param, uid should be int";
4012                     resultReceiver_.append(msg).append(LINE_BREAK);
4013                     APP_LOGE("%{public}s", msg.c_str());
4014                     return false;
4015                 }
4016                 break;
4017             }
4018             case 'h': {
4019                 resultReceiver_.append(HELP_MSG_BUNDLE_EVENT_CALLBACK);
4020                 return false;
4021             }
4022             default: {
4023                 std::string msg = "unsupported option";
4024                 resultReceiver_.append(msg).append(LINE_BREAK);
4025                 APP_LOGE("%{public}s", msg.c_str());
4026                 return false;
4027             }
4028         }
4029     }
4030     APP_LOGI("ParseEventCallbackOptions success");
4031     return true;
4032 }
4033 
ParseResetAOTCompileStatusOptions(std::string & bundleName,std::string & moduleName,int32_t & triggerMode,int32_t & uid)4034 bool BundleTestTool::ParseResetAOTCompileStatusOptions(std::string &bundleName, std::string &moduleName,
4035     int32_t &triggerMode, int32_t &uid)
4036 {
4037     int32_t opt;
4038     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_RESET_AOT_COMPILE_StATUS.c_str(),
4039         LONG_OPTIONS_RESET_AOT_COMPILE_StATUS, nullptr)) != -1) {
4040         switch (opt) {
4041             case 'b': {
4042                 bundleName = optarg;
4043                 break;
4044             }
4045             case 'm': {
4046                 moduleName = optarg;
4047                 break;
4048             }
4049             case 't': {
4050                 if (!OHOS::StrToInt(optarg, triggerMode)) {
4051                     std::string msg = "invalid param, triggerMode should be int";
4052                     resultReceiver_.append(msg).append(LINE_BREAK);
4053                     APP_LOGE("%{public}s", msg.c_str());
4054                     return false;
4055                 }
4056                 break;
4057             }
4058             case 'u': {
4059                 if (!OHOS::StrToInt(optarg, uid)) {
4060                     std::string msg = "invalid param, uid should be int";
4061                     resultReceiver_.append(msg).append(LINE_BREAK);
4062                     APP_LOGE("%{public}s", msg.c_str());
4063                     return false;
4064                 }
4065                 break;
4066             }
4067             case 'h': {
4068                 resultReceiver_.append(HELP_MSG_RESET_AOT_COMPILE_StATUS);
4069                 return false;
4070             }
4071             default: {
4072                 std::string msg = "unsupported option";
4073                 resultReceiver_.append(msg).append(LINE_BREAK);
4074                 APP_LOGE("%{public}s", msg.c_str());
4075                 return false;
4076             }
4077         }
4078     }
4079     APP_LOGI("ParseResetAOTCompileStatusOptions success");
4080     return true;
4081 }
4082 
Sleep(int32_t seconds)4083 void BundleTestTool::Sleep(int32_t seconds)
4084 {
4085     APP_LOGI("begin to sleep %{public}d seconds", seconds);
4086     std::this_thread::sleep_for(std::chrono::seconds(seconds));
4087     APP_LOGI("sleep done");
4088 }
4089 
CallRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)4090 ErrCode BundleTestTool::CallRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)
4091 {
4092     APP_LOGI("begin to call RegisterBundleEventCallback");
4093     std::string msg;
4094     bool ret = bundleMgrProxy_->RegisterBundleEventCallback(bundleEventCallback);
4095     if (!ret) {
4096         msg = "RegisterBundleEventCallback failed";
4097         resultReceiver_.append(msg).append(LINE_BREAK);
4098         APP_LOGE("%{public}s", msg.c_str());
4099         return OHOS::ERR_INVALID_VALUE;
4100     }
4101     msg = "RegisterBundleEventCallback success";
4102     resultReceiver_.append(msg).append(LINE_BREAK);
4103     APP_LOGI("%{public}s", msg.c_str());
4104     return OHOS::ERR_OK;
4105 }
4106 
CallUnRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)4107 ErrCode BundleTestTool::CallUnRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)
4108 {
4109     APP_LOGI("begin to call UnregisterBundleEventCallback");
4110     std::string msg;
4111     bool ret = bundleMgrProxy_->UnregisterBundleEventCallback(bundleEventCallback);
4112     if (!ret) {
4113         msg = "UnregisterBundleEventCallback failed";
4114         resultReceiver_.append(msg).append(LINE_BREAK);
4115         APP_LOGE("%{public}s", msg.c_str());
4116         return OHOS::ERR_INVALID_VALUE;
4117     }
4118     msg = "UnregisterBundleEventCallback success";
4119     resultReceiver_.append(msg).append(LINE_BREAK);
4120     APP_LOGI("%{public}s", msg.c_str());
4121     return OHOS::ERR_OK;
4122 }
4123 
HandleBundleEventCallback()4124 ErrCode BundleTestTool::HandleBundleEventCallback()
4125 {
4126     APP_LOGI("begin to HandleBundleEventCallback");
4127     bool onlyUnregister = false;
4128     int32_t uid = Constants::FOUNDATION_UID;
4129     if (!ParseEventCallbackOptions(onlyUnregister, uid)) {
4130         APP_LOGE("ParseEventCallbackOptions failed");
4131         return OHOS::ERR_INVALID_VALUE;
4132     }
4133     APP_LOGI("onlyUnregister : %{public}d, uid : %{public}d", onlyUnregister, uid);
4134     if (bundleMgrProxy_ == nullptr) {
4135         std::string msg = "bundleMgrProxy_ is nullptr";
4136         resultReceiver_.append(msg).append(LINE_BREAK);
4137         APP_LOGE("%{public}s", msg.c_str());
4138         return OHOS::ERR_INVALID_VALUE;
4139     }
4140     seteuid(uid);
4141     ErrCode ret;
4142     sptr<BundleEventCallbackImpl> bundleEventCallback = new (std::nothrow) BundleEventCallbackImpl();
4143     if (onlyUnregister) {
4144         // only call UnRegisterBundleEventCallback
4145         return CallUnRegisterBundleEventCallback(bundleEventCallback);
4146     }
4147     // call RegisterBundleEventCallback then call UnRegisterBundleEventCallback
4148     ret = CallRegisterBundleEventCallback(bundleEventCallback);
4149     if (ret != OHOS::ERR_OK) {
4150         return ret;
4151     }
4152     Sleep(SLEEP_SECONDS);
4153     ret = CallUnRegisterBundleEventCallback(bundleEventCallback);
4154     if (ret != OHOS::ERR_OK) {
4155         return ret;
4156     }
4157     Sleep(SLEEP_SECONDS);
4158     return OHOS::ERR_OK;
4159 }
4160 
ResetAOTCompileStatus()4161 ErrCode BundleTestTool::ResetAOTCompileStatus()
4162 {
4163     APP_LOGI("begin to ResetAOTCompileStatus");
4164     std::string bundleName;
4165     std::string moduleName;
4166     int32_t triggerMode = 0;
4167     int32_t uid = -1;
4168     if (!ParseResetAOTCompileStatusOptions(bundleName, moduleName, triggerMode, uid)) {
4169         APP_LOGE("ParseResetAOTCompileStatusOptions failed");
4170         return OHOS::ERR_INVALID_VALUE;
4171     }
4172     APP_LOGI("bundleName : %{public}s, moduleName : %{public}s, triggerMode : %{public}d",
4173         bundleName.c_str(), moduleName.c_str(), triggerMode);
4174     if (bundleMgrProxy_ == nullptr) {
4175         std::string msg = "bundleMgrProxy_ is nullptr";
4176         resultReceiver_.append(msg).append(LINE_BREAK);
4177         APP_LOGE("%{public}s", msg.c_str());
4178         return OHOS::ERR_INVALID_VALUE;
4179     }
4180     if (uid == -1) {
4181         int32_t userId = 100;
4182         uid = bundleMgrProxy_->GetUidByBundleName(bundleName, userId);
4183     }
4184     APP_LOGI("uid : %{public}d", uid);
4185     seteuid(uid);
4186     ErrCode ret = bundleMgrProxy_->ResetAOTCompileStatus(bundleName, moduleName, triggerMode);
4187     APP_LOGI("ret : %{public}d", ret);
4188     return OHOS::ERR_OK;
4189 }
4190 
SendCommonEvent()4191 ErrCode BundleTestTool::SendCommonEvent()
4192 {
4193     APP_LOGI("begin to SendCommonEvent");
4194     OHOS::AAFwk::Want want;
4195     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED);
4196     EventFwk::CommonEventData commonData { want };
4197     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
4198     return OHOS::ERR_OK;
4199 }
4200 
RunAsQueryDataGroupInfos()4201 ErrCode BundleTestTool::RunAsQueryDataGroupInfos()
4202 {
4203     APP_LOGI("RunAsQueryDataGroupInfos start");
4204     std::string bundleName;
4205     int32_t userId;
4206     int32_t appIndex;
4207     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
4208     if (result != OHOS::ERR_OK) {
4209         resultReceiver_.append(HELP_MSG_QUERY_DATA_GROUP_INFOS);
4210     } else {
4211         std::string msg;
4212         result = QueryDataGroupInfos(bundleName, userId, msg);
4213         if (result) {
4214             resultReceiver_ = STRING_QUERY_DATA_GROUP_INFOS_OK + msg;
4215             return ERR_OK;
4216         } else {
4217             resultReceiver_ = STRING_QUERY_DATA_GROUP_INFOS_NG + "\n";
4218         }
4219     }
4220     return OHOS::ERR_INVALID_VALUE;
4221 }
4222 
QueryDataGroupInfos(const std::string & bundleName,int32_t userId,std::string & msg)4223 bool BundleTestTool::QueryDataGroupInfos(const std::string &bundleName,
4224     int32_t userId, std::string& msg)
4225 {
4226     if (bundleMgrProxy_ == nullptr) {
4227         APP_LOGE("bundleMgrProxy_ is nullptr");
4228         return OHOS::ERR_INVALID_VALUE;
4229     }
4230     std::vector<DataGroupInfo> infos;
4231     bool ret = bundleMgrProxy_->QueryDataGroupInfos(bundleName, userId, infos);
4232     if (ret) {
4233         msg = "dataGroupInfos:\n{\n";
4234         for (const auto &dataGroupInfo : infos) {
4235             msg +="     ";
4236             msg += dataGroupInfo.ToString();
4237             msg += "\n";
4238         }
4239         msg += "}\n";
4240         return true;
4241     }
4242 
4243     return false;
4244 }
4245 
RunAsGetGroupDir()4246 ErrCode BundleTestTool::RunAsGetGroupDir()
4247 {
4248     APP_LOGI("RunAsGetGroupDir start");
4249     ErrCode result;
4250     std::string dataGroupId;
4251     int32_t counter = 0;
4252     while (true) {
4253         counter++;
4254         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_GROUP_DIR.c_str(),
4255             LONG_OPTIONS_GET_GROUP_DIR, nullptr);
4256         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4257         if (optind < 0 || optind > argc_) {
4258             return OHOS::ERR_INVALID_VALUE;
4259         }
4260         if (option == -1) {
4261             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4262                 resultReceiver_.append(HELP_MSG_GET_GROUP_DIR);
4263                 return OHOS::ERR_INVALID_VALUE;
4264             }
4265             break;
4266         }
4267         result = CheckGetGroupIdCorrectOption(option, dataGroupId);
4268         if (result != OHOS::ERR_OK) {
4269             resultReceiver_.append(HELP_MSG_GET_GROUP_DIR);
4270             return OHOS::ERR_INVALID_VALUE;
4271         }
4272     }
4273     std::string msg;
4274     bool ret = GetGroupDir(dataGroupId, msg);
4275     if (ret) {
4276         resultReceiver_ = STRING_GET_GROUP_DIR_OK + msg;
4277     } else {
4278         resultReceiver_ = STRING_GET_GROUP_DIR_NG + "\n";
4279         APP_LOGE("RunAsGetGroupDir fail");
4280         return OHOS::ERR_INVALID_VALUE;
4281     }
4282     return result;
4283 }
4284 
CheckGetGroupIdCorrectOption(int32_t option,std::string & dataGroupId)4285 ErrCode BundleTestTool::CheckGetGroupIdCorrectOption(int32_t option, std::string &dataGroupId)
4286 {
4287     ErrCode result = OHOS::ERR_OK;
4288     switch (option) {
4289         case 'h': {
4290             result = OHOS::ERR_INVALID_VALUE;
4291             break;
4292         }
4293         case 'd': {
4294             dataGroupId = optarg;
4295             if (dataGroupId.size() == 0) {
4296                 return OHOS::ERR_INVALID_VALUE;
4297             }
4298             break;
4299         }
4300         default: {
4301             result = OHOS::ERR_INVALID_VALUE;
4302             break;
4303         }
4304     }
4305     return result;
4306 }
4307 
GetGroupDir(const std::string & dataGroupId,std::string & msg)4308 bool BundleTestTool::GetGroupDir(const std::string &dataGroupId, std::string& msg)
4309 {
4310     if (bundleMgrProxy_ == nullptr) {
4311         APP_LOGE("bundleMgrProxy_ is nullptr");
4312         return OHOS::ERR_INVALID_VALUE;
4313     }
4314     std::string dir;
4315     bool ret = bundleMgrProxy_->GetGroupDir(dataGroupId, dir);
4316     if (ret) {
4317         msg = "group dir:\n";
4318         msg += dir;
4319         msg += "\n";
4320         return true;
4321     }
4322 
4323     return false;
4324 }
4325 
CheckGetBundleNameOption(int32_t option,std::string & bundleName)4326 ErrCode BundleTestTool::CheckGetBundleNameOption(int32_t option, std::string &bundleName)
4327 {
4328     ErrCode result = OHOS::ERR_OK;
4329     switch (option) {
4330         case 'h': {
4331             result = OHOS::ERR_INVALID_VALUE;
4332             break;
4333         }
4334         case 'n': {
4335             bundleName = optarg;
4336             if (bundleName.size() == 0) {
4337                 return OHOS::ERR_INVALID_VALUE;
4338             }
4339             break;
4340         }
4341         default: {
4342             result = OHOS::ERR_INVALID_VALUE;
4343             break;
4344         }
4345     }
4346     return result;
4347 }
4348 
CheckGetAssetAccessGroupsOption(int32_t option,const std::string & commandName,std::string & bundleName)4349 bool BundleTestTool::CheckGetAssetAccessGroupsOption(int32_t option, const std::string &commandName,
4350     std::string &bundleName)
4351 {
4352     bool ret = true;
4353     switch (option) {
4354         case 'h': {
4355             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
4356             ret = false;
4357             break;
4358         }
4359         case 'n': {
4360             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
4361             bundleName = optarg;
4362             break;
4363         }
4364         default: {
4365             std::string unknownOption = "";
4366             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
4367             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
4368             resultReceiver_.append(unknownOptionMsg);
4369             ret = false;
4370             break;
4371         }
4372     }
4373     return ret;
4374 }
4375 
RunAsGetAssetAccessGroups()4376 ErrCode BundleTestTool::RunAsGetAssetAccessGroups()
4377 {
4378     APP_LOGI("RunAsGetAssetAccessGroups start");
4379     int result = OHOS::ERR_OK;
4380     int counter = 0;
4381     std::string commandName = "getAssetAccessGroups";
4382     std::string bundleName = "";
4383     auto baseFlag = static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
4384     int32_t userId = BundleCommandCommon::GetCurrentUserId(Constants::UNSPECIFIED_USERID);
4385     while (true) {
4386         counter++;
4387         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_JSON_PROFILE.c_str(),
4388             LONG_OPTIONS_GET_ASSET_ACCESS_GROUPS, nullptr);
4389         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4390         if (optind < 0 || optind > argc_) {
4391             return OHOS::ERR_INVALID_VALUE;
4392         }
4393         if (option == -1) {
4394             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4395                 resultReceiver_.append(HELP_MSG_NO_GET_JSON_PROFILE_OPTION);
4396                 return OHOS::ERR_INVALID_VALUE;
4397             }
4398             break;
4399         }
4400         result = !CheckGetAssetAccessGroupsOption(option, commandName, bundleName)
4401             ? OHOS::ERR_INVALID_VALUE : result;
4402         APP_LOGE("bundleName = %{public}s", bundleName.c_str());
4403     }
4404     if (result != OHOS::ERR_OK) {
4405         resultReceiver_.append(HELP_MSG_GET_ASSET_ACCESS_GROUPS);
4406     } else {
4407         std::string results = "";
4408         BundleInfo bundleinfo;
4409         auto res = bundleMgrProxy_->GetBundleInfoV9(bundleName, baseFlag, bundleinfo, userId);
4410         if (res != OHOS::ERR_OK) {
4411             resultReceiver_.append(STRING_GET_ASSET_ACCESS_GROUPS_NG);
4412             return result;
4413         } else {
4414             resultReceiver_.append(STRING_GET_ASSET_ACCESS_GROUPS_OK);
4415             for (auto group : bundleinfo.applicationInfo.assetAccessGroups) {
4416                 results = group;
4417                 resultReceiver_.append(results);
4418                 resultReceiver_.append("\n");
4419             }
4420         }
4421     }
4422     return result;
4423 }
4424 
CheckSetAppDistributionTypesOption(int32_t option,const std::string & commandName,std::string & appDistributionTypes)4425 bool BundleTestTool::CheckSetAppDistributionTypesOption(int32_t option, const std::string &commandName,
4426     std::string &appDistributionTypes)
4427 {
4428     bool ret = true;
4429     switch (option) {
4430         case 'h': {
4431             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
4432             ret = false;
4433             break;
4434         }
4435         case 'a': {
4436             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
4437             appDistributionTypes = optarg;
4438             break;
4439         }
4440         default: {
4441             std::string unknownOption = "";
4442             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
4443             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
4444             resultReceiver_.append(unknownOptionMsg);
4445             ret = false;
4446             break;
4447         }
4448     }
4449     return ret;
4450 }
4451 
ProcessAppDistributionTypeEnums(std::vector<std::string> appDistributionTypeStrings,std::set<AppDistributionTypeEnum> & appDistributionTypeEnums)4452 bool BundleTestTool::ProcessAppDistributionTypeEnums(std::vector<std::string> appDistributionTypeStrings,
4453     std::set<AppDistributionTypeEnum> &appDistributionTypeEnums)
4454 {
4455     for (const std::string& item : appDistributionTypeStrings) {
4456         if (item ==
4457             std::to_string(static_cast<int32_t>(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_APP_GALLERY))) {
4458             appDistributionTypeEnums.insert(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_APP_GALLERY);
4459             continue;
4460         }
4461         if (item ==
4462             std::to_string(static_cast<int32_t>(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_ENTERPRISE))) {
4463             appDistributionTypeEnums.insert(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_ENTERPRISE);
4464             continue;
4465         }
4466         if (item ==
4467             std::to_string(static_cast<int32_t>(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_ENTERPRISE_NORMAL))) {
4468             appDistributionTypeEnums.insert(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_ENTERPRISE_NORMAL);
4469             continue;
4470         }
4471         if (item ==
4472             std::to_string(static_cast<int32_t>(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_ENTERPRISE_MDM))) {
4473             appDistributionTypeEnums.insert(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_ENTERPRISE_MDM);
4474             continue;
4475         }
4476         if (item ==
4477             std::to_string(static_cast<int32_t>(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_INTERNALTESTING))) {
4478             appDistributionTypeEnums.insert(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_INTERNALTESTING);
4479             continue;
4480         }
4481         if (item ==
4482             std::to_string(static_cast<int32_t>(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_CROWDTESTING))) {
4483             appDistributionTypeEnums.insert(AppDistributionTypeEnum::APP_DISTRIBUTION_TYPE_CROWDTESTING);
4484             continue;
4485         }
4486         return false;
4487     }
4488     return true;
4489 }
4490 
ReloadNativeTokenInfo()4491 void BundleTestTool::ReloadNativeTokenInfo()
4492 {
4493     const int32_t permsNum = 1;
4494     uint64_t tokenId;
4495     const char *perms[permsNum];
4496     perms[0] = "ohos.permission.MANAGE_EDM_POLICY";
4497     NativeTokenInfoParams infoInstance = {
4498         .dcapsNum = 0,
4499         .permsNum = permsNum,
4500         .aclsNum = 0,
4501         .dcaps = NULL,
4502         .perms = perms,
4503         .acls = NULL,
4504         .processName = "bundleTestToolProcess",
4505         .aplStr = "system_core",
4506     };
4507     tokenId = GetAccessTokenId(&infoInstance);
4508     SetSelfTokenID(tokenId);
4509     APP_LOGI("RunAsSetAppDistributionTypes ReloadNativeTokenInfo");
4510     OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo();
4511 }
4512 
RunAsSetAppDistributionTypes()4513 ErrCode BundleTestTool::RunAsSetAppDistributionTypes()
4514 {
4515     APP_LOGI("RunAsSetAppDistributionTypes start");
4516     ReloadNativeTokenInfo();
4517     int result = OHOS::ERR_OK;
4518     int counter = 0;
4519     std::string commandName = "setAppDistributionTypes";
4520     std::string appDistributionTypes = "";
4521     while (true) {
4522         counter++;
4523         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SET_APP_DISTRIBUTION_TYPES.c_str(),
4524             LONG_OPTIONS_SET_APP_DISTRIBUTION_TYPES, nullptr);
4525         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4526         if (optind < 0 || optind > argc_) {
4527             return OHOS::ERR_INVALID_VALUE;
4528         }
4529         if (option == -1) {
4530             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4531                 resultReceiver_.append(HELP_MSG_SET_APP_DISTRIBUTION_TYPES);
4532                 return OHOS::ERR_INVALID_VALUE;
4533             }
4534             break;
4535         }
4536         result = !CheckSetAppDistributionTypesOption(option, commandName, appDistributionTypes)
4537             ? OHOS::ERR_INVALID_VALUE : result;
4538         APP_LOGE("appDistributionTypes = %{public}s", appDistributionTypes.c_str());
4539     }
4540     if (result != OHOS::ERR_OK) {
4541         resultReceiver_.append(HELP_MSG_SET_APP_DISTRIBUTION_TYPES);
4542     } else {
4543         std::string results = "";
4544         std::vector<std::string> appDistributionTypeStrings;
4545         OHOS::SplitStr(appDistributionTypes, ",", appDistributionTypeStrings);
4546         std::set<AppDistributionTypeEnum> appDistributionTypeEnums;
4547         if (!ProcessAppDistributionTypeEnums(appDistributionTypeStrings, appDistributionTypeEnums)) {
4548             APP_LOGE("appDistributionTypes param %{public}s failed", appDistributionTypes.c_str());
4549             resultReceiver_.append(STRING_SET_APP_DISTRIBUTION_TYPES_NG);
4550             return OHOS::ERR_INVALID_VALUE;
4551         }
4552         auto res = bundleMgrProxy_->SetAppDistributionTypes(appDistributionTypeEnums);
4553         if (res != OHOS::ERR_OK) {
4554             resultReceiver_.append(STRING_SET_APP_DISTRIBUTION_TYPES_NG);
4555             return result;
4556         } else {
4557             resultReceiver_.append(STRING_SET_APP_DISTRIBUTION_TYPES_OK);
4558         }
4559     }
4560     return result;
4561 }
4562 
RunAsGetJsonProfile()4563 ErrCode BundleTestTool::RunAsGetJsonProfile()
4564 {
4565     APP_LOGI("RunAsGetJsonProfile start");
4566     int result = OHOS::ERR_OK;
4567     int counter = 0;
4568     std::string commandName = "getJsonProfile";
4569     std::string name = "";
4570     std::string bundleName = "";
4571     std::string moduleName = "";
4572     int jsonProfileType = -1;
4573     int userId = 100;
4574     APP_LOGD("RunAsGetStringCommand is start");
4575     while (true) {
4576         counter++;
4577         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_JSON_PROFILE.c_str(),
4578             LONG_OPTIONS_GET_JSON_PROFILE, nullptr);
4579         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4580         if (optind < 0 || optind > argc_) {
4581             return OHOS::ERR_INVALID_VALUE;
4582         }
4583         if (option == -1) {
4584             // When scanning the first argument
4585             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4586                 // 'GetStringById' with no option: GetStringById
4587                 // 'GetStringById' with a wrong argument: GetStringById
4588                 APP_LOGD("bundle_test_tool getStr with no option.");
4589                 resultReceiver_.append(HELP_MSG_NO_GET_JSON_PROFILE_OPTION);
4590                 return OHOS::ERR_INVALID_VALUE;
4591             }
4592             break;
4593         }
4594         int temp = 0;
4595         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4596             ? OHOS::ERR_INVALID_VALUE : result;
4597         moduleName = option == 'm' ? name : moduleName;
4598         bundleName = option == 'n' ? name : bundleName;
4599         userId = option == 'u' ? temp : userId;
4600         jsonProfileType = option == 'p' ? temp : jsonProfileType;
4601     }
4602 
4603     if (result != OHOS::ERR_OK) {
4604         resultReceiver_.append(HELP_MSG_GET_STRING);
4605     } else {
4606         std::string results = "";
4607         auto res = bundleMgrProxy_->GetJsonProfile(static_cast<ProfileType>(jsonProfileType),
4608             bundleName, moduleName, results, userId);
4609         if (res != OHOS::ERR_OK || results.empty()) {
4610             resultReceiver_.append(STRING_GET_JSON_PROFILE_NG);
4611             return result;
4612         }
4613         resultReceiver_.append(results);
4614         resultReceiver_.append("\n");
4615     }
4616     return result;
4617 }
4618 
RunGetUidByBundleName()4619 ErrCode BundleTestTool::RunGetUidByBundleName()
4620 {
4621     APP_LOGI("RunGetUidByBundleName start");
4622     int result = OHOS::ERR_OK;
4623     int counter = 0;
4624     std::string name = "";
4625     std::string commandName = "getUidByBundleName";
4626     std::string bundleName = "";
4627     int userId = 100;
4628     int appIndex = 0;
4629     APP_LOGD("RunGetIntCommand is start");
4630     bool flag = true;
4631     while (flag) {
4632         counter++;
4633         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_UID_BY_BUNDLENAME.c_str(),
4634             LONG_OPTIONS_GET_UID_BY_BUNDLENAME, nullptr);
4635         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4636         if (optind < 0 || optind > argc_) {
4637             return OHOS::ERR_INVALID_VALUE;
4638         }
4639         if (option == -1) {
4640             // When scanning the first argument
4641             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4642                 APP_LOGD("bundle_test_tool getUidByBundleName with no option.");
4643                 resultReceiver_.append(HELP_MSG_NO_GET_UID_BY_BUNDLENAME);
4644                 return OHOS::ERR_INVALID_VALUE;
4645             }
4646             break;
4647         }
4648         int temp = 0;
4649         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4650             ? OHOS::ERR_INVALID_VALUE : result;
4651         bundleName = option == 'n' ? name : bundleName;
4652         userId = option == 'u' ? temp : userId;
4653         appIndex = option == 'a' ? temp : appIndex;
4654     }
4655 
4656     if (result != OHOS::ERR_OK) {
4657         resultReceiver_.append(HELP_MSG_NO_GET_UID_BY_BUNDLENAME);
4658     } else {
4659         int32_t res = bundleMgrProxy_->GetUidByBundleName(bundleName, userId, appIndex);
4660         if (res == -1) {
4661             resultReceiver_.append(STRING_GET_UID_BY_BUNDLENAME_NG);
4662             return result;
4663         }
4664         resultReceiver_.append(std::to_string(res));
4665         resultReceiver_.append("\n");
4666     }
4667     return result;
4668 }
4669 
RunAsGetUninstalledBundleInfo()4670 ErrCode BundleTestTool::RunAsGetUninstalledBundleInfo()
4671 {
4672     APP_LOGI("RunAsGetUninstalledBundleInfo start");
4673     int result = OHOS::ERR_OK;
4674     int counter = 0;
4675     std::string bundleName = "";
4676     while (true) {
4677         counter++;
4678         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_UNINSTALLED_BUNDLE_INFO.c_str(),
4679             LONG_OPTIONS_UNINSTALLED_BUNDLE_INFO, nullptr);
4680         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4681         if (optind < 0 || optind > argc_) {
4682             return OHOS::ERR_INVALID_VALUE;
4683         }
4684         if (option == -1) {
4685             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4686                 resultReceiver_.append(HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION);
4687                 return OHOS::ERR_INVALID_VALUE;
4688             }
4689             break;
4690         }
4691         result = CheckGetBundleNameOption(option, bundleName);
4692         APP_LOGD("getUninstalledBundleInfo optind: %{public}s", bundleName.c_str());
4693     }
4694 
4695     if (result != OHOS::ERR_OK) {
4696         resultReceiver_.append(HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION);
4697     } else {
4698         BundleInfo bundleInfo;
4699         auto res = bundleMgrProxy_->GetUninstalledBundleInfo(bundleName, bundleInfo);
4700         if (res != OHOS::ERR_OK) {
4701             resultReceiver_.append(STRING_GET_UNINSTALLED_BUNDLE_INFO_NG);
4702             return result;
4703         }
4704         nlohmann::json jsonObject = bundleInfo;
4705         jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
4706         std::string results = jsonObject.dump(Constants::DUMP_INDENT);
4707         resultReceiver_.append(results);
4708         resultReceiver_.append("\n");
4709     }
4710     return result;
4711 }
4712 
RunAsGetOdid()4713 ErrCode BundleTestTool::RunAsGetOdid()
4714 {
4715     std::string commandName = "getOdid";
4716     int uid = Constants::INVALID_UID;
4717     int opt = 0;
4718 
4719     const std::map<char, OptionHandler> getOdidOptionHandlers = {
4720         {'u', [&uid, &commandName, this](const std::string& value) {
4721             bool ret;
4722             StringToInt(value, commandName, uid, ret); }}
4723     };
4724     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_ODID.c_str(), LONG_OPTIONS_GET_ODID, nullptr)) != -1) {
4725         auto it = getOdidOptionHandlers.find(opt);
4726         if (it != getOdidOptionHandlers.end()) {
4727             it->second(optarg);
4728         } else {
4729             resultReceiver_.append(HELP_MSG_GET_ODID);
4730             return OHOS::ERR_INVALID_VALUE;
4731         }
4732     }
4733     std::string odid;
4734     setuid(uid);
4735     auto result = bundleMgrProxy_->GetOdid(odid);
4736     setuid(Constants::ROOT_UID);
4737     if (result == ERR_OK) {
4738         resultReceiver_.append(STRING_GET_ODID_OK);
4739         resultReceiver_.append(odid + "\n");
4740     } else if (result == ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST) {
4741         resultReceiver_.append(STRING_GET_ODID_NG + "Please enter a valid uid\n");
4742     } else {
4743         resultReceiver_.append(STRING_GET_ODID_NG + "errCode is "+ std::to_string(result) + "\n");
4744     }
4745     return result;
4746 }
4747 
RunAsUpdateAppEncryptedStatus()4748 ErrCode BundleTestTool::RunAsUpdateAppEncryptedStatus()
4749 {
4750     std::string commandName = "updateAppEncryptedStatus";
4751     int appIndex = 0;
4752     int appEcrypted = 0;
4753     std::string bundleName;
4754     int opt = 0;
4755 
4756     const std::map<char, OptionHandler> optionHandlers = {
4757         {'a', [&appIndex, &commandName, this](const std::string& value) {
4758             bool ret;
4759             StringToInt(value, commandName, appIndex, ret); }},
4760         {'e', [&appEcrypted, &commandName, this](const std::string& value) {
4761             bool ret;
4762             StringToInt(value, commandName, appEcrypted, ret); }},
4763         {'n', [&bundleName, &commandName, this](const std::string& value) {
4764             bundleName = value; }},
4765 
4766     };
4767     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_UPDATE_APP_EXCRYPTED_STATUS.c_str(),
4768         LONG_OPTIONS_UPDATE_APP_EXCRYPTED_STATUS, nullptr)) != -1) {
4769         auto it = optionHandlers.find(opt);
4770         if (it != optionHandlers.end()) {
4771             it->second(optarg);
4772         } else {
4773             resultReceiver_.append(HELP_MSG_UPDATE_APP_EXCRYPTED_STATUS);
4774             return OHOS::ERR_INVALID_VALUE;
4775         }
4776     }
4777     setuid(CODE_PROTECT_UID);
4778     auto result = bundleMgrProxy_->UpdateAppEncryptedStatus(bundleName, static_cast<bool>(appEcrypted), appIndex);
4779     setuid(Constants::ROOT_UID);
4780     if (result == ERR_OK) {
4781         resultReceiver_.append(STRING_UPDATE_APP_EXCRYPTED_STATUS_SUCCESSFULLY);
4782     } else {
4783         resultReceiver_.append(
4784             STRING_UPDATE_APP_EXCRYPTED_STATUS_FAILED + "errCode is "+ std::to_string(result) + "\n");
4785     }
4786     return result;
4787 }
4788 
CheckImplicitQueryWantOption(int option,std::string & value)4789 ErrCode BundleTestTool::CheckImplicitQueryWantOption(int option, std::string &value)
4790 {
4791     ErrCode result = OHOS::ERR_OK;
4792     switch (option) {
4793         case 'n': {
4794             value = optarg;
4795             break;
4796         }
4797         case 'a': {
4798             value = optarg;
4799             break;
4800         }
4801         case 'e': {
4802             value = optarg;
4803             break;
4804         }
4805         case 'u': {
4806             value = optarg;
4807             break;
4808         }
4809         case 't': {
4810             value = optarg;
4811             break;
4812         }
4813         default: {
4814             std::string unknownOption = "";
4815             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
4816             resultReceiver_.append(unknownOptionMsg);
4817             result = OHOS::ERR_INVALID_VALUE;
4818             break;
4819         }
4820     }
4821     return result;
4822 }
4823 
ImplicitQuerySkillUriInfo(const std::string & bundleName,const std::string & action,const std::string & entity,const std::string & uri,const std::string & type,std::string & msg)4824 ErrCode BundleTestTool::ImplicitQuerySkillUriInfo(const std::string &bundleName,
4825     const std::string &action, const std::string &entity, const std::string &uri,
4826     const std::string &type, std::string &msg)
4827 {
4828     if (bundleMgrProxy_ == nullptr) {
4829         APP_LOGE("bundleMgrProxy_ is nullptr");
4830         return OHOS::ERR_INVALID_VALUE;
4831     }
4832     AAFwk::Want want;
4833     want.SetAction(action);
4834     want.AddEntity(entity);
4835     ElementName elementName("", bundleName, "", "");
4836     want.SetElement(elementName);
4837     want.SetUri(uri);
4838     want.SetType(type);
4839 
4840     int32_t userId = BundleCommandCommon::GetCurrentUserId(Constants::UNSPECIFIED_USERID);
4841     std::vector<AbilityInfo> abilityInfos;
4842     int32_t flags = static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL_URI);
4843     ErrCode res = bundleMgrProxy_->QueryAbilityInfosV9(want, flags, userId, abilityInfos);
4844     if (res != OHOS::ERR_OK) {
4845         return res;
4846     }
4847     for (auto &ability: abilityInfos) {
4848         msg += "Ability start\n";
4849         for (auto &uri: ability.skillUri) {
4850             msg += "{\n";
4851             msg += "    scheme: " + uri.scheme + "\n";
4852             msg += "    host: " + uri.host + "\n";
4853             msg += "    port: " + uri.port + "\n";
4854             msg += "    path: " + uri.path + "\n";
4855             msg += "    pathStartWith: " + uri.pathStartWith + "\n";
4856             msg += "    pathRegex: " + uri.pathRegex + "\n";
4857             msg += "    type: " + uri.type + "\n";
4858             msg += "    utd: " + uri.utd + "\n";
4859             msg += "    maxFileSupported: " + std::to_string(uri.maxFileSupported) + "\n";
4860             msg += "    linkFeature: " + uri.linkFeature + "\n";
4861             msg += "    isMatch: " + std::to_string(uri.isMatch) + "\n";
4862             msg += "}\n";
4863         }
4864         msg += "Ability end\n";
4865     }
4866     return res;
4867 }
4868 
RunAsImplicitQuerySkillUriInfo()4869 ErrCode BundleTestTool::RunAsImplicitQuerySkillUriInfo()
4870 {
4871     APP_LOGI("RunAsGetAbilityInfoWithSkillUriFlag start");
4872     int result = OHOS::ERR_OK;
4873     int counter = 0;
4874     std::string bundleName = "";
4875     std::string action = "";
4876     std::string entity = "";
4877     std::string uri = "";
4878     std::string type = "";
4879     while (true) {
4880         counter++;
4881         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO.c_str(),
4882             LONG_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO, nullptr);
4883         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4884         if (optind < 0 || optind > argc_) {
4885             return OHOS::ERR_INVALID_VALUE;
4886         }
4887         if (option == -1) {
4888             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4889                 resultReceiver_.append(HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO);
4890                 return OHOS::ERR_INVALID_VALUE;
4891             }
4892             break;
4893         }
4894         std::string value = "";
4895         result = CheckImplicitQueryWantOption(option, value);
4896         bundleName = option == 'n' ? value : bundleName;
4897         action = option == 'a' ? value : action;
4898         entity = option == 'e' ? value : entity;
4899         uri = option == 'u' ? value : uri;
4900         type = option == 't' ? value : type;
4901     }
4902     APP_LOGI("bundleName: %{public}s, action: %{public}s, entity: %{public}s, uri: %{public}s, type: %{public}s",
4903         bundleName.c_str(), action.c_str(), entity.c_str(), uri.c_str(), type.c_str());
4904     if (result != OHOS::ERR_OK) {
4905         resultReceiver_.append(HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO);
4906     } else {
4907         std::string msg;
4908         result = ImplicitQuerySkillUriInfo(bundleName, action, entity, uri, type, msg);
4909         if (result != OHOS::ERR_OK) {
4910             resultReceiver_.append(STRING_IMPLICIT_QUERY_SKILL_URI_INFO_NG);
4911         } else {
4912             resultReceiver_.append(msg);
4913         }
4914         resultReceiver_.append("\n");
4915     }
4916     return result;
4917 }
4918 
RunAsQueryAbilityInfoByContinueType()4919 ErrCode BundleTestTool::RunAsQueryAbilityInfoByContinueType()
4920 {
4921     APP_LOGI("RunAsQueryAbilityInfoByContinueType start");
4922     int result = OHOS::ERR_OK;
4923     int counter = 0;
4924     std::string commandName = "queryAbilityInfoByContinueType";
4925     std::string name = "";
4926     std::string bundleName = "";
4927     std::string continueType = "";
4928     int userId = 100;
4929     while (true) {
4930         counter++;
4931         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE.c_str(),
4932             LONG_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE, nullptr);
4933         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4934         if (optind < 0 || optind > argc_) {
4935             return OHOS::ERR_INVALID_VALUE;
4936         }
4937         if (option == -1) {
4938             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4939                 resultReceiver_.append(HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE);
4940                 return OHOS::ERR_INVALID_VALUE;
4941             }
4942             break;
4943         }
4944         int temp = 0;
4945         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4946             ? OHOS::ERR_INVALID_VALUE : result;
4947         bundleName = option == 'n' ? name : bundleName;
4948         continueType = option == 'c' ? name : continueType;
4949         userId = option == 'u' ? temp : userId;
4950     }
4951     APP_LOGI("bundleName: %{public}s, continueType: %{public}s, userId: %{public}d",
4952         bundleName.c_str(), continueType.c_str(), userId);
4953     if (result != OHOS::ERR_OK) {
4954         resultReceiver_.append(HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE);
4955     } else {
4956         AbilityInfo abilityInfo;
4957         result = bundleMgrProxy_->QueryAbilityInfoByContinueType(bundleName, continueType, abilityInfo, userId);
4958         if (result != OHOS::ERR_OK) {
4959             resultReceiver_.append(STRING_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE_NG);
4960         } else {
4961             nlohmann::json jsonObject = abilityInfo;
4962             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
4963             resultReceiver_.append(results);
4964         }
4965         resultReceiver_.append("\n");
4966     }
4967     return result;
4968 }
4969 
RunAsGetDirByBundleNameAndAppIndex()4970 ErrCode BundleTestTool::RunAsGetDirByBundleNameAndAppIndex()
4971 {
4972     APP_LOGI("RunAsGetDirByBundleNameAndAppIndex start");
4973     std::string commandName = "getDirByBundleNameAndAppIndex";
4974     int32_t result = OHOS::ERR_OK;
4975     int32_t counter = 0;
4976     std::string name = "";
4977     std::string bundleName = "";
4978     int32_t appIndex = 0;
4979     while (true) {
4980         counter++;
4981         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_DIR.c_str(),
4982             LONG_OPTIONS_GET_DIR, nullptr);
4983         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4984         if (optind < 0 || optind > argc_) {
4985             return OHOS::ERR_INVALID_VALUE;
4986         }
4987         if (option == -1) {
4988             // When scanning the first argument
4989             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4990                 APP_LOGD("bundle_test_tool getDirByBundleNameAndAppIndex with no option.");
4991                 resultReceiver_.append(HELP_MSG_GET_DIR_BY_BUNDLENAME_AND_APP_INDEX);
4992                 return OHOS::ERR_INVALID_VALUE;
4993             }
4994             break;
4995         }
4996         int temp = 0;
4997         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4998             ? OHOS::ERR_INVALID_VALUE : result;
4999         bundleName = option == 'n' ? name : bundleName;
5000         appIndex = option == 'a' ? temp : appIndex;
5001     }
5002     APP_LOGI("bundleName: %{public}s, appIndex: %{public}d", bundleName.c_str(), appIndex);
5003     if (result != OHOS::ERR_OK) {
5004         resultReceiver_.append(HELP_MSG_GET_DIR_BY_BUNDLENAME_AND_APP_INDEX);
5005     } else {
5006         std::string dataDir = "";
5007         BundleMgrClient client;
5008         result = client.GetDirByBundleNameAndAppIndex(bundleName, appIndex, dataDir);
5009         if (result == ERR_OK) {
5010             resultReceiver_.append(STRING_GET_DIR_OK);
5011             resultReceiver_.append(dataDir + "\n");
5012         } else if (result == ERR_BUNDLE_MANAGER_GET_DIR_INVALID_APP_INDEX) {
5013             resultReceiver_.append(STRING_GET_DIR_NG + "Please enter a valid appIndex\n");
5014         } else {
5015             resultReceiver_.append(STRING_GET_DIR_NG + "errCode is "+ std::to_string(result) + "\n");
5016         }
5017     }
5018     return result;
5019 }
5020 
RunAsGetAllBundleDirs()5021 ErrCode BundleTestTool::RunAsGetAllBundleDirs()
5022 {
5023     APP_LOGI("RunAsGetAllBundleDirs start");
5024     std::string commandName = "getAllBundleDirs";
5025     int32_t result = OHOS::ERR_OK;
5026     int32_t counter = 0;
5027     std::string name = "";
5028     int32_t userId = 0;
5029     while (true) {
5030         counter++;
5031         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_ALL_BUNDLE_DIRS.c_str(),
5032             LONG_OPTIONS_GET_ALL_BUNDLE_DIRS, nullptr);
5033         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5034         if (optind < 0 || optind > argc_) {
5035             return OHOS::ERR_INVALID_VALUE;
5036         }
5037         if (option == -1) {
5038             // When scanning the first argument
5039             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5040                 APP_LOGD("bundle_test_tool getAllBundleDirs with no option.");
5041                 resultReceiver_.append(HELP_MSG_GET_ALL_BUNDLE_DIRS);
5042                 return OHOS::ERR_INVALID_VALUE;
5043             }
5044             break;
5045         }
5046         int temp = 0;
5047         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
5048             ? OHOS::ERR_INVALID_VALUE : result;
5049         userId = option == 'u' ? temp : userId;
5050     }
5051     if (result != OHOS::ERR_OK) {
5052         resultReceiver_.append(HELP_MSG_GET_ALL_BUNDLE_DIRS);
5053     } else {
5054         std::string msg;
5055         result = GetAllBundleDirs(userId, msg);
5056         if (result == ERR_OK) {
5057             resultReceiver_.append(STRING_GET_ALL_BUNDLE_DIRS_OK + msg);
5058         } else {
5059             resultReceiver_.append(STRING_GET_ALL_BUNDLE_DIRS_NG + "errCode is "+ std::to_string(result) + "\n");
5060         }
5061     }
5062     APP_LOGI("RunAsGetAllBundleDirs end");
5063     return result;
5064 }
5065 
GetAllBundleDirs(int32_t userId,std::string & msg)5066 ErrCode BundleTestTool::GetAllBundleDirs(int32_t userId, std::string& msg)
5067 {
5068     BundleMgrClient client;
5069     std::vector<BundleDir> bundleDirs;
5070     auto ret = client.GetAllBundleDirs(userId, bundleDirs);
5071     if (ret == ERR_OK) {
5072         msg = "bundleDirs:\n{\n";
5073         for (const auto &bundleDir: bundleDirs) {
5074             msg +="     ";
5075             msg += bundleDir.ToString();
5076             msg += "\n";
5077         }
5078         msg += "}\n";
5079     }
5080     return ret;
5081 }
5082 
RunAsGetAllBundleCacheStat()5083 ErrCode BundleTestTool::RunAsGetAllBundleCacheStat()
5084 {
5085     APP_LOGI("RunAsGetAllBundleCacheStat start");
5086     std::string commandName = "getAllBundleCacheStat";
5087     int32_t result = OHOS::ERR_OK;
5088     int32_t counter = 0;
5089     std::string name = "";
5090     std::string msg;
5091     int uid = 0;
5092     while (counter <= 1) {
5093         counter++;
5094         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT.c_str(),
5095             LONG_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT, nullptr);
5096         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5097         if (optind < 0 || optind > argc_) {
5098             return OHOS::ERR_INVALID_VALUE;
5099         }
5100         if (option == -1) {
5101             // When scanning the first argument
5102             if ((counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5103                 msg = "with no option, set uid: 0";
5104                 resultReceiver_.append(msg + "\n");
5105                 setuid(uid);
5106                 break;
5107             }
5108             if (counter > 1) {
5109                 msg = "get uid: " + std::to_string(uid);
5110                 resultReceiver_.append(msg + "\n");
5111                 break;
5112             }
5113         }
5114         int temp = 0;
5115         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
5116             ? OHOS::ERR_INVALID_VALUE : result;
5117         uid = option == 'u' ? temp : uid;
5118         setuid(uid);
5119     }
5120     if (result != OHOS::ERR_OK) {
5121         resultReceiver_.append(HELP_MSG_GET_ALL_BUNDLE_CACHE_STAT);
5122     } else {
5123         msg = "";
5124         result = GetAllBundleCacheStat(msg);
5125         if (ERR_OK == result) {
5126             resultReceiver_.append(STRING_GET_ALL_BUNDLE_CACHE_STAT_OK + msg);
5127         } else {
5128             resultReceiver_.append(STRING_GET_ALL_BUNDLE_CACHE_STAT_NG + msg + "\n");
5129         }
5130     }
5131     APP_LOGI("RunAsGetAllBundleCacheStat end");
5132     return result;
5133 }
5134 
GetAllBundleCacheStat(std::string & msg)5135 ErrCode BundleTestTool::GetAllBundleCacheStat(std::string& msg)
5136 {
5137     if (bundleMgrProxy_ == nullptr) {
5138         APP_LOGE("bundleMgrProxy_ is nullptr");
5139         return OHOS::ERR_INVALID_VALUE;
5140     }
5141     sptr<ProcessCacheCallbackImpl> processCacheCallBack(new (std::nothrow) ProcessCacheCallbackImpl());
5142     if (processCacheCallBack == nullptr) {
5143         APP_LOGE("processCacheCallBack is null");
5144         return OHOS::ERR_INVALID_VALUE;
5145     }
5146     ErrCode ret = bundleMgrProxy_->GetAllBundleCacheStat(processCacheCallBack);
5147     uint64_t cacheSize = 0;
5148     if (ret ==ERR_OK) {
5149         msg += "clean exec wait \n";
5150         if (processCacheCallBack->WaitForStatCompletion()) {
5151             cacheSize = processCacheCallBack->GetCacheStat();
5152         } else {
5153             msg += "clean exec timeout \n";
5154         }
5155     }
5156     msg += "clean exec end \n";
5157     if (ret == ERR_OK) {
5158         msg += "AllBundleCacheStat:" + std::to_string(cacheSize) + "\n";
5159     } else {
5160         msg += "error code:" + std::to_string(ret) + "\n";
5161     }
5162     return ret;
5163 }
5164 
RunAsCleanAllBundleCache()5165 ErrCode BundleTestTool::RunAsCleanAllBundleCache()
5166 {
5167     APP_LOGI("RunAsCleanAllBundleCache start");
5168     std::string commandName = "cleanAllBundleCache";
5169     int32_t result = OHOS::ERR_OK;
5170     int32_t counter = 0;
5171     std::string name = "";
5172     std::string msg;
5173     int uid = 0;
5174     while (counter <= 1) {
5175         counter++;
5176         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_CLEAN_ALL_BUNDLE_CACHE.c_str(),
5177             LONG_OPTIONS_CLEAN_ALL_BUNDLE_CACHE, nullptr);
5178         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5179         if (optind < 0 || optind > argc_) {
5180             return OHOS::ERR_INVALID_VALUE;
5181         }
5182         if (option == -1) {
5183             // When scanning the first argument
5184             if ((counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5185                 msg = "with no option, set uid: 0";
5186                 resultReceiver_.append(msg + "\n");
5187                 setuid(uid);
5188                 break;
5189             }
5190             if (counter > 1) {
5191                 msg = "get uid: " + std::to_string(uid);
5192                 resultReceiver_.append(msg + "\n");
5193                 break;
5194             }
5195         }
5196         int temp = 0;
5197         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
5198             ? OHOS::ERR_INVALID_VALUE : result;
5199         uid = option == 'u' ? temp : uid;
5200         setuid(uid);
5201     }
5202     if (result != OHOS::ERR_OK) {
5203         resultReceiver_.append(HELP_MSG_CLEAN_ALL_BUNDLE_CACHE);
5204     } else {
5205         msg = "";
5206         result = CleanAllBundleCache(msg);
5207         if (ERR_OK == result) {
5208             resultReceiver_.append(STRING_CLEAN_ALL_BUNDLE_CACHE_OK + msg);
5209         } else {
5210             resultReceiver_.append(STRING_CLEAN_ALL_BUNDLE_CACHE_NG + msg + "\n");
5211         }
5212     }
5213     APP_LOGI("RunAsCleanAllBundleCache end");
5214     return result;
5215 }
5216 
CleanAllBundleCache(std::string & msg)5217 ErrCode BundleTestTool::CleanAllBundleCache(std::string& msg)
5218 {
5219     if (bundleMgrProxy_ == nullptr) {
5220         APP_LOGE("bundleMgrProxy_ is nullptr");
5221         return false;
5222     }
5223     sptr<ProcessCacheCallbackImpl> processCacheCallBack(new (std::nothrow) ProcessCacheCallbackImpl());
5224     if (processCacheCallBack == nullptr) {
5225         APP_LOGE("processCacheCallBack is null");
5226         return OHOS::ERR_INVALID_VALUE;
5227     }
5228 
5229     ErrCode ret = bundleMgrProxy_->CleanAllBundleCache(processCacheCallBack);
5230     int32_t cleanRet = 0;
5231     std::string callbackMsg = "";
5232     if (ret ==ERR_OK) {
5233         callbackMsg += "clean exec wait \n";
5234         if (processCacheCallBack->WaitForCleanCompletion()) {
5235             cleanRet = processCacheCallBack->GetDelRet();
5236         } else {
5237             callbackMsg += "clean exec timeout \n";
5238             cleanRet = -1;
5239         }
5240     }
5241     callbackMsg += "clean exec end \n";
5242     if (ret != ERR_OK || cleanRet != ERR_OK) {
5243         callbackMsg += "return code:" + std::to_string(ret) + " cleanRet code:" + std::to_string(cleanRet) + "\n";
5244         msg = callbackMsg;
5245         return OHOS::ERR_INVALID_VALUE;
5246     }
5247     return ERR_OK;
5248 }
5249 
RunAsIsBundleInstalled()5250 ErrCode BundleTestTool::RunAsIsBundleInstalled()
5251 {
5252     APP_LOGI("RunAsIsBundleInstalled start");
5253     std::string commandName = "isBundleInstalled";
5254     int32_t result = OHOS::ERR_OK;
5255     int32_t counter = 0;
5256     std::string name = "";
5257     std::string bundleName = "";
5258     int32_t userId = BundleCommandCommon::GetCurrentUserId(Constants::UNSPECIFIED_USERID);
5259     int32_t appIndex = 0;
5260     while (true) {
5261         counter++;
5262         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_IS_BUNDLE_INSTALLED.c_str(),
5263             LONG_OPTIONS_IS_BUNDLE_INSTALLED, nullptr);
5264         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5265         if (optind < 0 || optind > argc_) {
5266             return OHOS::ERR_INVALID_VALUE;
5267         }
5268         if (option == -1) {
5269             // When scanning the first argument
5270             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5271                 APP_LOGD("bundle_test_tool isBundleInstalled with no option.");
5272                 resultReceiver_.append(HELP_MSG_IS_BUNDLE_INSTALLED);
5273                 return OHOS::ERR_INVALID_VALUE;
5274             }
5275             break;
5276         }
5277         int temp = 0;
5278         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
5279             ? OHOS::ERR_INVALID_VALUE : result;
5280         bundleName = option == 'n' ? name : bundleName;
5281         userId = option == 'u' ? temp : userId;
5282         appIndex = option == 'a' ? temp : appIndex;
5283     }
5284     APP_LOGI("bundleName: %{public}s, appIndex: %{public}d, userId: %{public}d", bundleName.c_str(), appIndex, userId);
5285     if (result != OHOS::ERR_OK) {
5286         resultReceiver_.append(HELP_MSG_IS_BUNDLE_INSTALLED);
5287     } else {
5288         bool isBundleInstalled = false;
5289         result = bundleMgrProxy_->IsBundleInstalled(bundleName, userId, appIndex, isBundleInstalled);
5290         if (result == ERR_OK) {
5291             resultReceiver_.append(STRING_IS_BUNDLE_INSTALLED_OK);
5292             resultReceiver_.append("isBundleInstalled: ");
5293             resultReceiver_.append(isBundleInstalled ? "true\n" : "false\n");
5294         } else {
5295             resultReceiver_.append(STRING_IS_BUNDLE_INSTALLED_NG + "errCode is "+ std::to_string(result) + "\n");
5296         }
5297     }
5298     return result;
5299 }
5300 
RunAsGetCompatibleDeviceType()5301 ErrCode BundleTestTool::RunAsGetCompatibleDeviceType()
5302 {
5303     APP_LOGI("RunAsGetCompatibleDeviceType start");
5304     std::string commandName = "getCompatibleDeviceType";
5305     int32_t result = OHOS::ERR_OK;
5306     int32_t counter = 0;
5307     std::string name = "";
5308     std::string bundleName = "";
5309     while (true) {
5310         counter++;
5311         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_COMPATIBLE_DEVICE_TYPE.c_str(),
5312             LONG_OPTIONS_GET_COMPATIBLE_DEVICE_TYPE, nullptr);
5313         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5314         if (optind < 0 || optind > argc_) {
5315             return OHOS::ERR_INVALID_VALUE;
5316         }
5317         if (option == -1) {
5318             // When scanning the first argument
5319             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5320                 APP_LOGD("bundle_test_tool getCompatibleDeviceType with no option.");
5321                 resultReceiver_.append(HELP_MSG_GET_COMPATIBLE_DEVICE_TYPE);
5322                 return OHOS::ERR_INVALID_VALUE;
5323             }
5324             break;
5325         }
5326         int temp = 0;
5327         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
5328             ? OHOS::ERR_INVALID_VALUE : result;
5329         bundleName = option == 'n' ? name : bundleName;
5330     }
5331     APP_LOGI("bundleName: %{public}s", bundleName.c_str());
5332     if (result != OHOS::ERR_OK) {
5333         resultReceiver_.append(HELP_MSG_GET_COMPATIBLE_DEVICE_TYPE);
5334     } else {
5335         std::string deviceType;
5336         result = bundleMgrProxy_->GetCompatibleDeviceType(bundleName, deviceType);
5337         if (result == ERR_OK) {
5338             resultReceiver_.append(STRING_GET_COMPATIBLE_DEVICE_TYPE_OK);
5339             resultReceiver_.append("deviceType: ");
5340             resultReceiver_.append(deviceType + "\n");
5341         } else {
5342             resultReceiver_.append(STRING_GET_COMPATIBLE_DEVICE_TYPE_NG + "errCode is "+ std::to_string(result) + "\n");
5343         }
5344     }
5345     return result;
5346 }
5347 
InnerGetSimpleAppInfoForUid(const int32_t & option,std::vector<std::int32_t> & uids)5348 ErrCode BundleTestTool::InnerGetSimpleAppInfoForUid(const int32_t &option, std::vector<std::int32_t> &uids)
5349 {
5350     std::string commandName = "getSimpleAppInfoForUid";
5351     int32_t uid = Constants::FOUNDATION_UID;
5352     switch (option) {
5353         case 'u': {
5354             std::string arrayUId = optarg;
5355             std::stringstream array(arrayUId);
5356             std::string object;
5357             bool ret = true;
5358             while (getline(array, object, ',')) {
5359                 StringToInt(object, commandName, uid, ret);
5360                 if (!ret) {
5361                     resultReceiver_.append(HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID);
5362                     return OHOS::ERR_INVALID_VALUE;
5363                 }
5364                 uids.emplace_back(uid);
5365             }
5366             APP_LOGD("bundle_test_tool %{public}s -u %{public}s", commandName.c_str(), argv_[optind - 1]);
5367             break;
5368         }
5369         default: {
5370             resultReceiver_.append(HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID);
5371             return OHOS::ERR_INVALID_VALUE;
5372         }
5373     }
5374     return OHOS::ERR_OK;
5375 }
5376 
RunAsGetSimpleAppInfoForUid()5377 ErrCode BundleTestTool::RunAsGetSimpleAppInfoForUid()
5378 {
5379     APP_LOGI("RunAsGetSimpleAppInfoForUid start");
5380     std::vector<std::int32_t> uids;
5381     int32_t counter = 0;
5382     while (counter <= 1) {
5383         counter++;
5384         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID.c_str(),
5385             LONG_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID, nullptr);
5386         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5387         if (optind < 0 || optind > argc_) {
5388             return OHOS::ERR_INVALID_VALUE;
5389         }
5390         if (option == -1) {
5391             // When scanning the first argument
5392             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5393                 APP_LOGD("bundle_test_tool getSimpleAppInfoForUid with no option.");
5394                 resultReceiver_.append(HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID);
5395                 return OHOS::ERR_INVALID_VALUE;
5396             }
5397             break;
5398         }
5399         auto ret = InnerGetSimpleAppInfoForUid(option, uids);
5400         if (ret != OHOS::ERR_OK) {
5401             return ret;
5402         }
5403     }
5404     std::vector<SimpleAppInfo> simpleAppInfo;
5405     auto result = bundleMgrProxy_->GetSimpleAppInfoForUid(uids, simpleAppInfo);
5406     if (result == ERR_OK) {
5407         resultReceiver_.append(STRING_GET_SIMPLE_APP_INFO_FOR_UID_OK);
5408         for (size_t i = 0; i < simpleAppInfo.size(); i++) {
5409             resultReceiver_.append(simpleAppInfo[i].ToString() + "\n");
5410         }
5411     } else {
5412         resultReceiver_.append(STRING_GET_SIMPLE_APP_INFO_FOR_UID_NG + "errCode is "+ std::to_string(result) + "\n");
5413     }
5414     APP_LOGI("RunAsGetSimpleAppInfoForUid end");
5415     return result;
5416 }
5417 
RunAsGetBundleNameByAppId()5418 ErrCode BundleTestTool::RunAsGetBundleNameByAppId()
5419 {
5420     APP_LOGI("RunAsGetBundleNameByAppId start");
5421     std::string appId;
5422     std::string bundleName;
5423     int32_t counter = 0;
5424     while (true) {
5425         counter++;
5426         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLENAME_BY_APPID.c_str(),
5427             LONG_OPTIONS_GET_BUNDLENAME_BY_APPID, nullptr);
5428         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5429         if (optind < 0 || optind > argc_) {
5430             return OHOS::ERR_INVALID_VALUE;
5431         }
5432         if (option == -1) {
5433             // When scanning the first argument
5434             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5435                 APP_LOGD("bundle_test_tool isBundleInstalled with no option.");
5436                 resultReceiver_.append(HELP_MSG_GET_BUNDLENAME_BY_APPID);
5437                 return OHOS::ERR_INVALID_VALUE;
5438             }
5439             break;
5440         }
5441         switch (option) {
5442             case 'a': {
5443                 appId = optarg;
5444                 break;
5445             }
5446             default: {
5447                 resultReceiver_.append(HELP_MSG_GET_BUNDLENAME_BY_APPID);
5448                 return OHOS::ERR_INVALID_VALUE;
5449             }
5450         }
5451     }
5452     auto result = bundleMgrProxy_->GetBundleNameByAppId(appId, bundleName);
5453     if (result == ERR_OK) {
5454         resultReceiver_.append(STRING_GET_BUNDLENAME_BY_APPID_OK);
5455         resultReceiver_.append(bundleName + "\n");
5456     } else {
5457         resultReceiver_.append(STRING_GET_BUNDLENAME_BY_APPID_NG + "errCode is "+ std::to_string(result) + "\n");
5458     }
5459     APP_LOGI("RunAsGetBundleNameByAppId end");
5460     return result;
5461 }
5462 
UninstallPreInstallBundleOperation(const std::string & bundleName,InstallParam & installParam) const5463 ErrCode BundleTestTool::UninstallPreInstallBundleOperation(
5464     const std::string &bundleName, InstallParam &installParam) const
5465 {
5466     sptr<StatusReceiverImpl> statusReceiver(new (std::nothrow) StatusReceiverImpl());
5467     if (statusReceiver == nullptr) {
5468         APP_LOGE("statusReceiver is null");
5469         return IStatusReceiver::ERR_UNKNOWN;
5470     }
5471 
5472     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(statusReceiver));
5473     if (recipient == nullptr) {
5474         APP_LOGE("recipient is null");
5475         return IStatusReceiver::ERR_UNKNOWN;
5476     }
5477     bundleInstallerProxy_->AsObject()->AddDeathRecipient(recipient);
5478     bundleInstallerProxy_->Uninstall(bundleName, installParam, statusReceiver);
5479     return statusReceiver->GetResultCode();
5480 }
5481 
CheckUnisntallCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)5482 bool BundleTestTool::CheckUnisntallCorrectOption(
5483     int option, const std::string &commandName, int &temp, std::string &name)
5484 {
5485     bool ret = true;
5486     switch (option) {
5487         case 'h': {
5488             ret = false;
5489             break;
5490         }
5491         case 'n': {
5492             name = optarg;
5493             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
5494             break;
5495         }
5496         case 'u':{
5497             if (!OHOS::StrToInt(optarg, temp)) {
5498                 APP_LOGE("bundle_test_tool %{public}s with error -u %{private}s", commandName.c_str(), optarg);
5499                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
5500                 ret = false;
5501             }
5502             break;
5503         }
5504         case 'f':{
5505             if (!OHOS::StrToInt(optarg, temp)) {
5506                 APP_LOGE("bundle_test_tool %{public}s with error -f %{private}s", commandName.c_str(), optarg);
5507                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
5508                 ret = false;
5509             }
5510             break;
5511         }
5512         default: {
5513             ret = false;
5514             std::string unknownOption = "";
5515             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
5516             APP_LOGW("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
5517             resultReceiver_.append(unknownOptionMsg);
5518             break;
5519         }
5520     }
5521     return ret;
5522 }
5523 
RunAsUninstallPreInstallBundleCommand()5524 ErrCode BundleTestTool::RunAsUninstallPreInstallBundleCommand()
5525 {
5526     int32_t result = OHOS::ERR_OK;
5527     int counter = 0;
5528     std::string name = "";
5529     std::string bundleName = "";
5530     int32_t userId = 100;
5531     int forceValue = 0;
5532     while (counter <= MAX_PARAMS_FOR_UNINSTALL) {
5533         counter++;
5534         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_PREINSTALL.c_str(), LONG_OPTIONS_PREINSTALL, nullptr);
5535         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
5536         if (optind < 0 || optind > argc_) {
5537             return OHOS::ERR_INVALID_VALUE;
5538         }
5539         if (option == -1) {
5540             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
5541                 APP_LOGD("bundle_test_tool uninstallPreInstallBundle with no option.");
5542                 resultReceiver_.append(HELP_MSG_UNINSTALL_PREINSTALL_BUNDLE);
5543                 return OHOS::ERR_INVALID_VALUE;
5544             }
5545             break;
5546         }
5547         int temp = 0;
5548         result = !CheckUnisntallCorrectOption(option, UNINSTALL_PREINSTALL_BUNDLE, temp, name)
5549             ? OHOS::ERR_INVALID_VALUE : result;
5550         bundleName = option == 'n' ? name : bundleName;
5551         userId = option == 'u' ? temp : userId;
5552         forceValue = option == 'f' ? temp : forceValue;
5553     }
5554     if (result != OHOS::ERR_OK || bundleName == "") {
5555         resultReceiver_.append(HELP_MSG_UNINSTALL_PREINSTALL_BUNDLE);
5556         return OHOS::ERR_INVALID_VALUE;
5557     }
5558 
5559     InstallParam installParam;
5560     installParam.userId = userId;
5561     if (forceValue > 0) {
5562         OHOS::system::SetParameter(IS_ENTERPRISE_DEVICE, "true");
5563         installParam.parameters.emplace(Constants::VERIFY_UNINSTALL_FORCED_KEY,
5564             Constants::VERIFY_UNINSTALL_FORCED_VALUE);
5565     }
5566     result = UninstallPreInstallBundleOperation(bundleName, installParam);
5567     if (result == OHOS::ERR_OK) {
5568         resultReceiver_ = STRING_UNINSTALL_PREINSTALL_BUNDLE_SUCCESSFULLY + "\n";
5569     } else {
5570         resultReceiver_ = STRING_UNINSTALL_PREINSTALL_BUNDLE_FAILED + "\n";
5571         resultReceiver_.append(GetMessageFromCode(result));
5572     }
5573     return result;
5574 }
5575 } // AppExecFwk
5576 } // OHOS