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