1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "bundle_test_tool.h"
16 
17 #include <chrono>
18 #include <cstdlib>
19 #include <cstring>
20 #include <future>
21 #include <getopt.h>
22 #include <iostream>
23 #include <set>
24 #include <sstream>
25 #include <thread>
26 #include <unistd.h>
27 #include <vector>
28 
29 #include "app_log_wrapper.h"
30 #include "appexecfwk_errors.h"
31 #include "bundle_command_common.h"
32 #include "bundle_death_recipient.h"
33 #include "bundle_mgr_client.h"
34 #include "bundle_mgr_proxy.h"
35 #include "bundle_tool_callback_stub.h"
36 #include "common_event_manager.h"
37 #include "common_event_support.h"
38 #include "data_group_info.h"
39 #include "directory_ex.h"
40 #include "parameter.h"
41 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
42 #include "quick_fix_status_callback_host_impl.h"
43 #endif
44 #include "status_receiver_impl.h"
45 #include "string_ex.h"
46 #include "json_util.h"
47 
48 namespace OHOS {
49 namespace AppExecFwk {
50 namespace {
51 using OptionHandler = std::function<void(const std::string&)>;
52 
53 const std::string LINE_BREAK = "\n";
54 constexpr int32_t SLEEP_SECONDS = 20;
55 // param
56 const int32_t INDEX_OFFSET = 2;
57 // quick fix error code
58 const int32_t ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED = 801;
59 const int32_t INITIAL_SANDBOX_APP_INDEX = 1000;
60 // quick fix error message
61 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR = "error: quick fix internal error.\n";
62 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR = "error: param error.\n";
63 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED = "error: profile parse failed.\n";
64 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME = "error: not same bundle name.\n";
65 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME = "error: not same version code.\n";
66 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME = "error: not same version name.\n";
67 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME =
68     "error: not same patch version code.\n";
69 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME =
70     "error: not same patch version name.\n";
71 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME = "error: not same patch type.\n";
72 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE = "error: unknown quick fix type.\n";
73 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE = "error: patch so incompatible.\n";
74 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME = "error: same moduleName.\n";
75 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST = "error: bundle name is not existed.\n";
76 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST = "error: module name is not existed.\n";
77 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME = "error: signature is not existed.\n";
78 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED = "error: quick fix add hqf failed.\n";
79 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED =
80     "error: quick fix save innerAppQuickFix failed.\n";
81 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR =
82     "error: quick fix version code require greater than original hqf.\n";
83 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE = "error: no this quick fix info in database.\n";
84 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS = "error: wrong quick fix status.\n";
85 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO =
86     "error: cannot obtain the bundleInfo from data mgr.\n";
87 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED = "error: quick fix remove path failed.\n";
88 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED = "error: extract diff files failed.\n";
89 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED = "error: apply diff patch failed.\n";
90 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN = "error: unknown.\n";
91 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED = "feature is not supported.\n";
92 const std::string MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT = "error: quick fix operation time out.\n";
93 const std::string MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED = "error: bundleMgr service is dead.\n";
94 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE =
95     "error: hotreload not support release bundle.\n";
96 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED = "error: patch type already existed.\n";
97 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED =
98     "error: hotreload type already existed.\n";
99 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO =
100     "error: no patch info in bundleInfo.\n";
101 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED = "error: quick fix move hqf file failed.\n";
102 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED = "error: quick fix create path failed.\n";
103 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB =
104     "error: old patch or hot reload in db.\n";
105 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SEND_REQUEST_FAILED = "error: send request failed.\n";
106 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REAL_PATH_FAILED = "error: obtain realpath failed.\n";
107 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATH = "error: input invalid path.\n";
108 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OPEN_SOURCE_FILE_FAILED = "error: open source file failed.\n";
109 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_FD_FAILED = "error: create file descriptor failed.\n";
110 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_TARGET_DIR = "error: invalid designated target dir\n";
111 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_TARGET_DIR_FAILED = "error: create target dir failed.\n";
112 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PERMISSION_DENIED = "error: quick fix permission denied.\n";
113 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_WRITE_FILE_FAILED = "error: write file to target dir failed.\n";
114 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED =
115     "error: the hqf of release hap cannot contains resources/rawfile.\n";
116 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM =
117     "error: invalid param for setting debug mode.\n";
118 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR =
119     "error: internal error for setting debug mode.\n";
120 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR = "error: parcel error for setting debug mode.\n";
121 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR = "error: send request error.\n";
122 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED = "error: uid check failed.\n";
123 
124 static const std::string TOOL_NAME = "bundle_test_tool";
125 static const std::string HELP_MSG =
126     "usage: bundle_test_tool <command> <options>\n"
127     "These are common bundle_test_tool commands list:\n"
128     "  help                             list available commands\n"
129     "  setrm                            set module isRemovable by given bundle name and module name\n"
130     "  getrm                            obtain the value of isRemovable by given bundle name and module name\n"
131     "  installSandbox                   indicates install sandbox\n"
132     "  uninstallSandbox                 indicates uninstall sandbox\n"
133     "  dumpSandbox                      indicates dump sandbox info\n"
134     "  getStr                           obtain the value of label by given bundle name, module name and label id\n"
135     "  getIcon                          obtain the value of icon by given bundle name, module name, "
136     "density and icon id\n"
137     "  addAppInstallRule                obtain the value of install controlRule by given some app id "
138     "control rule type, user id and euid\n"
139     "  getAppInstallRule                obtain the value of install controlRule by given some app id "
140     "rule type, user id and euid\n"
141     "  deleteAppInstallRule             obtain the value of install controlRule by given some app id "
142     "user id and euid\n"
143     "  cleanAppInstallRule              obtain the value of install controlRule by given rule type "
144     "user id and euid\n"
145     "  addAppRunningRule                obtain the value of app running control rule "
146     "by given controlRule user id and euidn\n"
147     "  deleteAppRunningRule             obtain the value of app running control rule "
148     "by given controlRule user id and euid\n"
149     "  cleanAppRunningRule              obtain the value of app running control "
150     "rule by given user id and euid\n"
151     "  getAppRunningControlRule         obtain the value of app running control rule "
152     "by given user id and euid and some app id\n"
153     "  getAppRunningControlRuleResult   obtain the value of app running control rule "
154     "by given bundleName user id, euid and controlRuleResult\n"
155     "  deployQuickFix                   deploy a quick fix patch of an already installed bundle\n"
156     "  switchQuickFix                   switch a quick fix patch of an already installed bundle\n"
157     "  deleteQuickFix                   delete a quick fix patch of an already installed bundle\n"
158     "  setDebugMode                     enable signature debug mode\n"
159     "  getBundleStats                   get bundle stats\n"
160     "  getAppProvisionInfo              get appProvisionInfo\n"
161     "  getDistributedBundleName         get distributedBundleName\n"
162     "  eventCB                          register then unregister bundle event callback\n"
163     "  resetAOTCompileStatus            reset AOTCompileStatus\n"
164     "  sendCommonEvent                  send common event\n"
165     "  queryDataGroupInfos              obtain the data group infos of the application\n"
166     "  getGroupDir                      obtain the data group dir path by data group id\n"
167     "  getJsonProfile                   obtain the json string of the specified module\n"
168     "  getOdid                          obtain the odid of the application\n"
169     "  getUidByBundleName               obtain the uid string of the specified bundle\n"
170     "  implicitQuerySkillUriInfo        obtain the skill uri info of the implicit query ability\n"
171     "  queryAbilityInfoByContinueType   get ability info by continue type\n"
172     "  cleanBundleCacheFilesAutomatic   clear cache data of a specified size\n"
173     "  getContinueBundleName            get continue bundle name list\n"
174     "  getBundleNameByAppId             get bundlename by appid or appIdentifier\n";
175 
176 const std::string HELP_MSG_GET_REMOVABLE =
177     "usage: bundle_test_tool getrm <options>\n"
178     "eg:bundle_test_tool getrm -m <module-name> -n <bundle-name> \n"
179     "options list:\n"
180     "  -h, --help                             list available commands\n"
181     "  -n, --bundle-name  <bundle-name>       get isRemovable by moduleNmae and bundleName\n"
182     "  -m, --module-name <module-name>        get isRemovable by moduleNmae and bundleName\n";
183 
184 const std::string HELP_MSG_NO_REMOVABLE_OPTION =
185     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
186     "and a module name with '-m' or '--module-name' \n";
187 
188 const std::string HELP_MSG_SET =
189     "usage: bundle_test_tool setrm <options>\n"
190     "eg:bundle_test_tool setrm -m <module-name> -n <bundle-name> -i 1\n"
191     "options list:\n"
192     "  -h, --help                               list available commands\n"
193     "  -n, --bundle-name  <bundle-name>         set isRemovable by moduleNmae and bundleName\n"
194     "  -i, --is-removable <is-removable>        set isRemovable  0 or 1\n"
195     "  -m, --module-name <module-name>          set isRemovable by moduleNmae and bundleName\n";
196 
197 const std::string HELP_MSG_INSTALL_SANDBOX =
198     "usage: bundle_test_tool installSandbox <options>\n"
199     "options list:\n"
200     "  -h, --help                             list available commands\n"
201     "  -u, --user-id <user-id>                specify a user id\n"
202     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n"
203     "  -d, --dlp-type <dlp-type>              specify type of the sandbox application\n";
204 
205 const std::string HELP_MSG_UNINSTALL_SANDBOX =
206     "usage: bundle_test_tool uninstallSandbox <options>\n"
207     "options list:\n"
208     "  -h, --help                             list available commands\n"
209     "  -u, --user-id <user-id>                specify a user id\n"
210     "  -a, --app-index <app-index>            specify a app index\n"
211     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
212 
213 const std::string HELP_MSG_DUMP_SANDBOX =
214     "usage: bundle_test_tool dumpSandbox <options>\n"
215     "options list:\n"
216     "  -h, --help                             list available commands\n"
217     "  -u, --user-id <user-id>                specify a user id\n"
218     "  -a, --app-index <app-index>            specify a app index\n"
219     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
220 
221 const std::string HELP_MSG_GET_STRING =
222     "usage: bundle_test_tool getStr <options>\n"
223     "eg:bundle_test_tool getStr -m <module-name> -n <bundle-name> -u <user-id> -i --id <id> \n"
224     "options list:\n"
225     "  -h, --help                             list available commands\n"
226     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
227     "  -m, --module-name <module-name>        specify module name of the application\n"
228     "  -u, --user-id <user-id>                specify a user id\n"
229     "  -i, --id <id>                          specify a label id of the application\n";
230 
231 const std::string HELP_MSG_GET_ICON =
232     "usage: bundle_test_tool getIcon <options>\n"
233     "eg:bundle_test_tool getIcon -m <module-name> -n <bundle-name> -u <user-id> -d --density <density> -i --id <id> \n"
234     "options list:\n"
235     "  -h, --help                             list available commands\n"
236     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
237     "  -m, --module-name <module-name>        specify module name of the application\n"
238     "  -u, --user-id <user-id>                specify a user id\n"
239     "  -d, --density <density>                specify a density\n"
240     "  -i, --id <id>                          specify a icon id of the application\n";
241 
242 const std::string HELP_MSG_NO_GETSTRING_OPTION =
243     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
244     "and a module name with '-m' or '--module-name' \n"
245     "and a userid with '-u' or '--user-id' \n"
246     "and a labelid with '-i' or '--id' \n";
247 
248 const std::string HELP_MSG_NO_GETICON_OPTION =
249     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
250     "and a module name with '-m' or '--module-name' \n"
251     "and a userid with '-u' or '--user-id' \n"
252     "and a density with '-d' or '--density' \n"
253     "and a iconid with '-i' or '--id' \n";
254 
255 const std::string HELP_MSG_ADD_INSTALL_RULE =
256     "usage: bundle_test_tool <options>\n"
257     "eg:bundle_test_tool addAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
258     "options list:\n"
259     "  -h, --help                             list available commands\n"
260     "  -a, --app-id <app-id>                  specify app id of the application\n"
261     "  -e, --euid <eu-id>                     default euid value is 3057\n"
262     "  -t, --control-rule-type                specify control type of the application\n"
263     "  -u, --user-id <user-id>                specify a user id\n";
264 
265 const std::string HELP_MSG_GET_INSTALL_RULE =
266     "usage: bundle_test_tool <options>\n"
267     "eg:bundle_test_tool getAppInstallRule -t <control-rule-type> -u <user-id> \n"
268     "options list:\n"
269     "  -h, --help                             list available commands\n"
270     "  -e, --euid <eu-id>                     default euid value is 3057\n"
271     "  -t, --control-rule-type                specify control type of the application\n"
272     "  -u, --user-id <user-id>                specify a user id\n";
273 
274 const std::string HELP_MSG_DELETE_INSTALL_RULE =
275     "usage: bundle_test_tool <options>\n"
276     "eg:bundle_test_tool deleteAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
277     "options list:\n"
278     "  -h, --help                             list available commands\n"
279     "  -e, --euid <eu-id>                     default euid value is 3057\n"
280     "  -a, --app-id <app-id>                  specify app id of the application\n"
281     "  -t, --control-rule-type                specify control type of the application\n"
282     "  -u, --user-id <user-id>                specify a user id\n";
283 
284 const std::string HELP_MSG_CLEAN_INSTALL_RULE =
285     "usage: bundle_test_tool <options>\n"
286     "eg:bundle_test_tool cleanAppInstallRule -t <control-rule-type> -u <user-id> \n"
287     "options list:\n"
288     "  -h, --help                             list available commands\n"
289     "  -e, --euid <eu-id>                     default euid value is 3057\n"
290     "  -t, --control-rule-type                specify control type of the application\n"
291     "  -u, --user-id <user-id>                specify a user id\n";
292 
293 const std::string HELP_MSG_ADD_APP_RUNNING_RULE =
294     "usage: bundle_test_tool <options>\n"
295     "eg:bundle_test_tool addAppRunningRule -c <control-rule> -u <user-id> \n"
296     "options list:\n"
297     "  -h, --help                             list available commands\n"
298     "  -e, --euid <eu-id>                     default euid value is 3057\n"
299     "  -c, --control-rule                     specify control rule of the application\n"
300     "  -u, --user-id <user-id>                specify a user id\n";
301 
302 const std::string HELP_MSG_DELETE_APP_RUNNING_RULE =
303     "usage: bundle_test_tool <options>\n"
304     "eg:bundle_test_tool deleteAppRunningRule -c <control-rule> -u <user-id> \n"
305     "options list:\n"
306     "  -h, --help                             list available commands\n"
307     "  -e, --euid <eu-id>                     default euid value is 3057\n"
308     "  -c, --control-rule                     specify control rule of the application\n"
309     "  -u, --user-id <user-id>                specify a user id\n";
310 
311 const std::string HELP_MSG_CLEAN_APP_RUNNING_RULE =
312     "usage: bundle_test_tool <options>\n"
313     "eg:bundle_test_tool cleanAppRunningRule -u <user-id> \n"
314     "options list:\n"
315     "  -h, --help                             list available commands\n"
316     "  -e, --euid <eu-id>                     default euid value is 3057\n"
317     "  -u, --user-id <user-id>                specify a user id\n";
318 
319 const std::string HELP_MSG_GET_APP_RUNNING_RULE =
320     "usage: bundle_test_tool <options>\n"
321     "eg:bundle_test_tool getAppRunningControlRule -u <user-id> \n"
322     "options list:\n"
323     "  -h, --help                             list available commands\n"
324     "  -e, --euid <eu-id>                     default euid value is 3057\n"
325     "  -u, --user-id <user-id>                specify a user id\n";
326 
327 const std::string HELP_MSG_GET_APP_RUNNING_RESULT_RULE =
328     "usage: bundle_test_tool <options>\n"
329     "eg:bundle_test_tool getAppRunningControlRuleResult -n <bundle-name> \n"
330     "options list:\n"
331     "  -h, --help                             list available commands\n"
332     "  -e, --euid <eu-id>                     default euid value is 3057\n"
333     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
334     "  -u, --user-id <user-id>                specify a user id\n";
335 
336 const std::string HELP_MSG_AUTO_CLEAN_CACHE_RULE =
337     "usage: bundle_test_tool <options>\n"
338     "eg:bundle_test_tool cleanBundleCacheFilesAutomatic -s <cache-size> \n"
339     "options list:\n"
340     "  -h, --help                             list available commands\n"
341     "  -s, --cache-size <cache-size>          specify the cache size that needs to be cleaned\n";
342 
343 const std::string HELP_MSG_NO_ADD_INSTALL_RULE_OPTION =
344     "error: you must specify a app id with '-a' or '--app-id' \n"
345     "and a control type with '-t' or '--control-rule-type' \n"
346     "and a userid with '-u' or '--user-id' \n";
347 
348 const std::string HELP_MSG_NO_GET_INSTALL_RULE_OPTION =
349     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
350     "and a userid with '-u' or '--user-id' \n";
351 
352 const std::string HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION =
353     "error: you must specify a control type with '-a' or '--app-id' \n"
354     "and a userid with '-u' or '--user-id' \n";
355 
356 const std::string HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION =
357     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
358     "and a userid with '-u' or '--user-id' \n";
359 
360 const std::string HELP_MSG_NO_APP_RUNNING_RULE_OPTION =
361     "error: you must specify a app running type with '-c' or '--control-rule' \n"
362     "and a userid with '-u' or '--user-id' \n";
363 
364 const std::string HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION =
365     "error: you must specify a app running type with a userid '-u' or '--user-id \n";
366 
367 const std::string HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION =
368     "error: you must specify a app running type with '-a' or '--app-id' \n"
369     "and a userid with '-u' or '--user-id' \n";
370 
371 const std::string HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION =
372     "error: you must specify a app running type with '-n' or '--bundle-name' \n"
373     "and a userid with '-u' or '--user-id' \n";
374 
375 const std::string HELP_MSG_NO_AUTO_CLEAN_CACHE_OPTION =
376     "error: you must specify a cache size with '-s' or '--cache-size' \n";
377 
378 const std::string HELP_MSG_DEPLOY_QUICK_FIX =
379     "usage: bundle_test_tool deploy quick fix <options>\n"
380     "eg:bundle_test_tool deployQuickFix -p <quickFixPath> \n"
381     "options list:\n"
382     "  -h, --help                             list available commands\n"
383     "  -p, --patch-path  <patch-path>         specify patch path of the patch\n"
384     "  -d, --debug  <debug>                   specify deploy mode, 0 represents release, 1 represents debug\n";
385 
386 const std::string HELP_MSG_SWITCH_QUICK_FIX =
387     "usage: bundle_test_tool switch quick fix <options>\n"
388     "eg:bundle_test_tool switchQuickFix -n <bundle-name> \n"
389     "options list:\n"
390     "  -h, --help                             list available commands\n"
391     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n"
392     "  -e, --enbale  <enable>                 enable a deployed patch of disable an under using patch,\n"
393     "                                         1 represents enable and 0 represents disable\n";
394 
395 const std::string HELP_MSG_DELETE_QUICK_FIX =
396     "usage: bundle_test_tool delete quick fix <options>\n"
397     "eg:bundle_test_tool deleteQuickFix -n <bundle-name> \n"
398     "options list:\n"
399     "  -h, --help                             list available commands\n"
400     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n";
401 
402 const std::string HELP_MSG_SET_DEBUG_MODE =
403     "usage: bundle_test_tool setDebugMode <options>\n"
404     "eg:bundle_test_tool setDebugMode -e <0/1>\n"
405     "options list:\n"
406     "  -h, --help                             list available commands\n"
407     "  -e, --enable  <enable>                 enable signature debug mode, 1 represents enable debug mode and 0\n"
408     "                                         represents disable debug mode\n";
409 
410 const std::string HELP_MSG_GET_BUNDLE_STATS =
411     "usage: bundle_test_tool getBundleStats <options>\n"
412     "eg:bundle_test_tool getBundleStats -n <bundle-name>\n"
413     "options list:\n"
414     "  -h, --help                             list available commands\n"
415     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
416     "  -u, --user-id <user-id>                specify a user id\n"
417     "  -a, --app-index <app-index>            specify a app index\n";
418 
419 
420 const std::string HELP_MSG_GET_APP_PROVISION_INFO =
421     "usage: bundle_test_tool getAppProvisionInfo <options>\n"
422     "eg:bundle_test_tool getAppProvisionInfo -n <bundle-name>\n"
423     "options list:\n"
424     "  -h, --help                             list available commands\n"
425     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
426     "  -u, --user-id <user-id>                specify a user id\n";
427 
428 const std::string HELP_MSG_GET_DISTRIBUTED_BUNDLE_NAME =
429     "usage: bundle_test_tool getDistributedBundleName <options>\n"
430     "eg:bundle_test_tool getDistributedBundleName -n <network-id> -a <access-token-id>\n"
431     "options list:\n"
432     "  -h, --help                                   list available commands\n"
433     "  -n, --network-id  <network-id>               specify networkId of the application\n"
434     "  -a, --access-token-id <access-token-id>      specify a accessTokenId of the application \n";
435 
436 const std::string HELP_MSG_BUNDLE_EVENT_CALLBACK =
437     "usage: bundle_test_tool eventCB <options>\n"
438     "options list:\n"
439     "  -h, --help           list available commands\n"
440     "  -o, --onlyUnregister only call unregister, default will call register then unregister\n"
441     "  -u, --uid            specify a uid, default is foundation uid\n";
442 
443 const std::string HELP_MSG_RESET_AOT_COMPILE_StATUS =
444     "usage: bundle_test_tool resetAOTCompileStatus <options>\n"
445     "options list:\n"
446     "  -h, --help           list available commands\n"
447     "  -b, --bundle-name    specify bundle name\n"
448     "  -m, --module-name    specify module name\n"
449     "  -t, --trigger-mode   specify trigger mode, default is 0\n"
450     "  -u, --uid            specify a uid, default is bundleName's uid\n";
451 
452 const std::string HELP_MSG_GET_PROXY_DATA =
453     "usage: bundle_test_tool getProxyDataInfos <options>\n"
454     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -u <user-id>\n"
455     "options list:\n"
456     "  -h, --help                             list available commands\n"
457     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
458     "  -m, --module-name <module-name>        specify module name of the application\n"
459     "  -u, --user-id <user-id>                specify a user id\n";
460 
461 const std::string HELP_MSG_GET_ALL_PROXY_DATA =
462     "usage: bundle_test_tool getAllProxyDataInfos <options>\n"
463     "eg:bundle_test_tool getProxyDataInfos -u <user-id>\n"
464     "options list:\n"
465     "  -h, --help                             list available commands\n"
466     "  -u, --user-id <user-id>                specify a user id\n";
467 
468 const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION =
469     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
470 
471 const std::string HELP_MSG_NO_NETWORK_ID_OPTION =
472     "error: you must specify a network id with '-n' or '--network-id' \n";
473 
474 const std::string HELP_MSG_NO_ACCESS_TOKEN_ID_OPTION =
475     "error: you must specify a access token id with '-n' or '--access-token-id' \n";
476 
477 const std::string HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE =
478     "usage: bundle_test_tool setExtNameOrMimeTypeToApp <options>\n"
479     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -a <ability-name>\n"
480     "options list:\n"
481     "  -h, --help                             list available commands\n"
482     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
483     "  -m, --module-name <module-name>        specify module name of the application\n"
484     "  -a, --ability-name <ability-name>      specify ability name of the application\n"
485     "  -e, --ext-name <ext-name>              specify the ext-name\n"
486     "  -t, --mime-type <mime-type>            specify the mime-type\n";
487 
488 const std::string HELP_MSG_DEL_EXT_NAME_OR_MIME_TYPE =
489     "usage: bundle_test_tool setExtNameOrMimeTypeToApp <options>\n"
490     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -a <ability-name>\n"
491     "options list:\n"
492     "  -h, --help                             list available commands\n"
493     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
494     "  -m, --module-name <module-name>        specify module name of the application\n"
495     "  -a, --ability-name <ability-name>      specify ability name of the application\n"
496     "  -e, --ext-name <ext-name>              specify the ext-name\n"
497     "  -t, --mime-type <mime-type>            specify the mime-type\n";
498 
499 const std::string HELP_MSG_QUERY_DATA_GROUP_INFOS =
500     "usage: bundle_test_tool queryDataGroupInfos <options>\n"
501     "eg:bundle_test_tool queryDataGroupInfos -n <bundle-name> -u <user-id>\n"
502     "options list:\n"
503     "  -h, --help                             list available commands\n"
504     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
505     "  -u, --user-id <user-id>                specify a user id\n";
506 
507 const std::string HELP_MSG_GET_GROUP_DIR =
508     "usage: bundle_test_tool getGroupDir <options>\n"
509     "eg:bundle_test_tool getGroupDir -d <data-group-id>\n"
510     "options list:\n"
511     "  -h, --help                             list available commands\n"
512     "  -d, --data-group-id  <data-group-id>       specify bundle name of the application\n";
513 
514 const std::string HELP_MSG_NO_GET_UID_BY_BUNDLENAME =
515     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
516     "and a userId with '-u' or '--user-id' \n"
517     "and a appIndex with '-a' or '--app-index' \n";
518 
519 const std::string HELP_MSG_NO_GET_JSON_PROFILE_OPTION =
520     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
521     "and a module name with '-m' or '--module-name' \n"
522     "and a userId with '-u' or '--user-id' \n"
523     "and a json profile type with '-p' or '--profile-type' \n";
524 
525 const std::string HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION =
526     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
527 
528 const std::string HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO =
529     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
530     "and a action with '-a' or '--action' \n"
531     "and a entity with '-e' or '--entity' \n";
532 
533 const std::string HELP_MSG_GET_ODID =
534     "usage: bundle_test_tool getOdid <options>\n"
535     "eg:bundle_test_tool getOdid -u <uid>\n"
536     "options list:\n"
537     "  -h, --help               list available commands\n"
538     "  -u, --uid  <uid>         specify uid of the application\n";
539 
540 const std::string HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE =
541     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
542     "and a continueType with '-c' or '--continue-type' \n"
543     "and a userId with '-u' or '--user-id' \n";
544 
545 const std::string HELP_MSG_GET_BUNDLENAME_BY_APPID =
546     "usage: bundle_test_tool getBundleNameByAppId <options>\n"
547     "eg:bundle_test_tool getBundleNameByAppId -a <app-id>\n"
548     "options list:\n"
549     "  -a, --app-id <app-id>            specify a app index or app identifier\n";
550 
551 const std::string STRING_GET_BUNDLENAME_BY_APPID_OK = "getBundleNameByAppId is ok \n";
552 const std::string STRING_GET_BUNDLENAME_BY_APPID_NG =
553     "error: failed to getBundleNameByAppId \n";
554 const std::string STRING_SET_REMOVABLE_OK = "set removable is ok \n";
555 const std::string STRING_SET_REMOVABLE_NG = "error: failed to set removable \n";
556 const std::string STRING_GET_REMOVABLE_OK = "get removable is ok \n";
557 const std::string STRING_GET_REMOVABLE_NG = "error: failed to get removable \n";
558 const std::string STRING_REQUIRE_CORRECT_VALUE =
559     "error: option requires a correct value or note that\n"
560     "the difference in expressions between short option and long option. \n";
561 
562 const std::string STRING_INSTALL_SANDBOX_SUCCESSFULLY = "install sandbox app successfully \n";
563 const std::string STRING_INSTALL_SANDBOX_FAILED = "install sandbox app failed \n";
564 
565 const std::string STRING_UNINSTALL_SANDBOX_SUCCESSFULLY = "uninstall sandbox app successfully\n";
566 const std::string STRING_UNINSTALL_SANDBOX_FAILED = "uninstall sandbox app failed\n";
567 
568 const std::string STRING_DUMP_SANDBOX_FAILED = "dump sandbox app info failed\n";
569 
570 const std::string STRING_GET_STRING_NG = "error: failed to get label \n";
571 
572 const std::string STRING_GET_ICON_NG = "error: failed to get icon \n";
573 
574 const std::string STRING_ADD_RULE_NG = "error: failed to add rule \n";
575 const std::string STRING_GET_RULE_NG = "error: failed to get rule \n";
576 const std::string STRING_DELETE_RULE_NG = "error: failed to delete rule \n";
577 
578 const std::string STRING_DEPLOY_QUICK_FIX_OK = "deploy quick fix successfully\n";
579 const std::string STRING_DEPLOY_QUICK_FIX_NG = "deploy quick fix failed\n";
580 const std::string HELP_MSG_NO_QUICK_FIX_PATH_OPTION = "need a quick fix patch path\n";
581 const std::string STRING_SWITCH_QUICK_FIX_OK = "switch quick fix successfully\n";
582 const std::string STRING_SWITCH_QUICK_FIX_NG = "switch quick fix failed\n";
583 const std::string STRING_DELETE_QUICK_FIX_OK = "delete quick fix successfully\n";
584 const std::string STRING_DELETE_QUICK_FIX_NG = "delete quick fix failed\n";
585 
586 const std::string STRING_SET_DEBUG_MODE_OK = "set debug mode successfully\n";
587 const std::string STRING_SET_DEBUG_MODE_NG = "set debug mode failed\n";
588 
589 const std::string STRING_GET_BUNDLE_STATS_OK = "get bundle stats successfully\n";
590 const std::string STRING_GET_BUNDLE_STATS_NG = "get bundle stats failed\n";
591 
592 const std::string STRING_GET_APP_PROVISION_INFO_OK = "get appProvisionInfo successfully\n";
593 const std::string STRING_GET_APP_PROVISION_INFO_NG = "get appProvisionInfo failed\n";
594 
595 const std::string STRING_QUERY_DATA_GROUP_INFOS_OK = "queryDataGroupInfos successfully\n";
596 const std::string STRING_QUERY_DATA_GROUP_INFOS_NG = "queryDataGroupInfos failed\n";
597 
598 const std::string STRING_GET_GROUP_DIR_OK = "getGroupDir successfully\n";
599 const std::string STRING_GET_GROUP_DIR_NG = "getGroupDir failed\n";
600 
601 const std::string STRING_GET_JSON_PROFILE_NG = "getJsonProfile failed\n";
602 
603 const std::string STRING_GET_UNINSTALLED_BUNDLE_INFO_NG = "getUninstalledBundleInfo failed\n";
604 
605 const std::string STRING_GET_ODID_OK = "getOdid successfully\n";
606 const std::string STRING_GET_ODID_NG = "getOdid failed\n";
607 
608 const std::string STRING_GET_UID_BY_BUNDLENAME_NG = "getUidByBundleName failed\n";
609 
610 const std::string STRING_IMPLICIT_QUERY_SKILL_URI_INFO_NG =
611     "implicitQuerySkillUriInfo failed\n";
612 
613 const std::string STRING_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE_NG =
614     "queryAbilityInfoByContinueType failed\n";
615 
616 const std::string HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION =
617     "error: you must specify a control type with '-n' or '--network-id' \n"
618     "and a accessTokenId with '-a' or '--access-token-id' \n";
619 
620 const std::string GET_DISTRIBUTED_BUNDLE_NAME_COMMAND_NAME = "getDistributedBundleName";
621 
622 const std::string STRING_GET_DISTRIBUTED_BUNDLE_NAME_OK = "get distributedBundleName successfully\n";
623 const std::string STRING_GET_DISTRIBUTED_BUNDLE_NAME_NG = "get distributedBundleName failed\n";
624 
625 const std::string STRING_GET_PROXY_DATA_NG = "get proxyData failed";
626 
627 const std::string GET_BUNDLE_STATS_ARRAY[] = {
628     "app data size: ",
629     "user data size: ",
630     "distributed data size: ",
631     "database size: ",
632     "cache size: "
633 };
634 
635 const std::string GET_RM = "getrm";
636 const std::string SET_RM = "setrm";
637 const std::string INSTALL_SANDBOX = "installSandbox";
638 const std::string UNINSTALL_SANDBOX = "uninstallSandbox";
639 const std::string DUMP_SANDBOX = "dumpSandbox";
640 
641 const std::string SHORT_OPTIONS = "hn:m:a:d:u:i:";
642 const struct option LONG_OPTIONS[] = {
643     {"help", no_argument, nullptr, 'h'},
644     {"bundle-name", required_argument, nullptr, 'n'},
645     {"module-name", required_argument, nullptr, 'm'},
646     {"ability-name", required_argument, nullptr, 'a'},
647     {"device-id", required_argument, nullptr, 'd'},
648     {"user-id", required_argument, nullptr, 'u'},
649     {"is-removable", required_argument, nullptr, 'i'},
650     {nullptr, 0, nullptr, 0},
651 };
652 
653 const std::string SHORT_OPTIONS_GET_BUNDLENAME_BY_APPID = "ha:";
654 const struct option LONG_OPTIONS_GET_BUNDLENAME_BY_APPID[] = {
655     {"help", no_argument, nullptr, 'h'},
656     {"app-id", required_argument, nullptr, 'a'},
657     {nullptr, 0, nullptr, 0},
658 };
659 
660 const std::string SHORT_OPTIONS_SANDBOX = "hn:d:u:a:";
661 const struct option LONG_OPTIONS_SANDBOX[] = {
662     {"help", no_argument, nullptr, 'h'},
663     {"bundle-name", required_argument, nullptr, 'n'},
664     {"user-id", required_argument, nullptr, 'u'},
665     {"dlp-type", required_argument, nullptr, 'd'},
666     {"app-index", required_argument, nullptr, 'a'},
667     {nullptr, 0, nullptr, 0},
668 };
669 
670 const std::string SHORT_OPTIONS_GET = "hn:m:u:i:d:";
671 const struct option LONG_OPTIONS_GET[] = {
672     {"help", no_argument, nullptr, 'h'},
673     {"bundle-name", required_argument, nullptr, 'n'},
674     {"module-name", required_argument, nullptr, 'm'},
675     {"user-id", required_argument, nullptr, 'u'},
676     {"id", required_argument, nullptr, 'i'},
677     {"density", required_argument, nullptr, 'd'},
678     {nullptr, 0, nullptr, 0},
679 };
680 
681 const std::string SHORT_OPTIONS_RULE = "ha:c:n:e:r:t:u:";
682 const struct option LONG_OPTIONS_RULE[] = {
683     {"help", no_argument, nullptr, 'h'},
684     {"app-id", required_argument, nullptr, 'a'},
685     {"control-rule", required_argument, nullptr, 'c'},
686     {"bundle-name", required_argument, nullptr, 'n'},
687     {"bundle-name", required_argument, nullptr, 'n'},
688     {"euid", required_argument, nullptr, 'e'},
689     {"control-rule-type", required_argument, nullptr, 't'},
690     {"user-id", required_argument, nullptr, 'u'},
691     {nullptr, 0, nullptr, 0},
692 };
693 
694 const std::string SHORT_OPTIONS_AUTO_CLEAN_CACHE = "hs:";
695 const struct option LONG_OPTIONS_AUTO_CLEAN_CACHE[] = {
696     {"help", no_argument, nullptr, 'h'},
697     {"cache-size", required_argument, nullptr, 's'},
698     {nullptr, 0, nullptr, 0},
699 };
700 
701 const std::string SHORT_OPTIONS_QUICK_FIX = "hp:n:e:d:";
702 const struct option LONG_OPTIONS_QUICK_FIX[] = {
703     {"help", no_argument, nullptr, 'h'},
704     {"patch-path", required_argument, nullptr, 'p'},
705     {"bundle-name", required_argument, nullptr, 'n'},
706     {"enable", required_argument, nullptr, 'e'},
707     {"debug", required_argument, nullptr, 'd'},
708     {nullptr, 0, nullptr, 0},
709 };
710 
711 const std::string SHORT_OPTIONS_DEBUG_MODE = "he:";
712 const struct option LONG_OPTIONS_DEBUG_MODE[] = {
713     {"help", no_argument, nullptr, 'h'},
714     {"enable", required_argument, nullptr, 'e'},
715     {nullptr, 0, nullptr, 0},
716 };
717 
718 const std::string SHORT_OPTIONS_GET_BUNDLE_STATS = "hn:u:a:";
719 const struct option LONG_OPTIONS_GET_BUNDLE_STATS[] = {
720     {"help", no_argument, nullptr, 'h'},
721     {"bundle-name", required_argument, nullptr, 'n'},
722     {"user-id", required_argument, nullptr, 'u'},
723     {"app-index", required_argument, nullptr, 'a'},
724     {nullptr, 0, nullptr, 0},
725 };
726 
727 const std::string SHORT_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME = "hn:a:";
728 const struct option LONG_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME[] = {
729     {"help", no_argument, nullptr, 'h'},
730     {"network-id", required_argument, nullptr, 'n'},
731     {"access-token-id", required_argument, nullptr, 'a'},
732     {nullptr, 0, nullptr, 0},
733 };
734 
735 const std::string SHORT_OPTIONS_BUNDLE_EVENT_CALLBACK = "hou:";
736 const struct option LONG_OPTIONS_BUNDLE_EVENT_CALLBACK[] = {
737     {"help", no_argument, nullptr, 'h'},
738     {"onlyUnregister", no_argument, nullptr, 'o'},
739     {"uid", required_argument, nullptr, 'u'},
740     {nullptr, 0, nullptr, 0},
741 };
742 
743 const std::string SHORT_OPTIONS_RESET_AOT_COMPILE_StATUS = "b:m:t:u:";
744 const struct option LONG_OPTIONS_RESET_AOT_COMPILE_StATUS[] = {
745     {"help", no_argument, nullptr, 'h'},
746     {"bundle-name", required_argument, nullptr, 'b'},
747     {"module-name", required_argument, nullptr, 'm'},
748     {"trigger-mode", required_argument, nullptr, 't'},
749     {"uid", required_argument, nullptr, 'u'},
750     {nullptr, 0, nullptr, 0},
751 };
752 
753 const std::string SHORT_OPTIONS_PROXY_DATA = "hn:m:u:";
754 const struct option LONG_OPTIONS_PROXY_DATA[] = {
755     {"help", no_argument, nullptr, 'h'},
756     {"bundle-name", required_argument, nullptr, 'n'},
757     {"module-name", required_argument, nullptr, 'm'},
758     {"user-id", required_argument, nullptr, 'u'},
759     {nullptr, 0, nullptr, 0},
760 };
761 
762 const std::string SHORT_OPTIONS_ALL_PROXY_DATA = "hu:";
763 const struct option LONG_OPTIONS_ALL_PROXY_DATA[] = {
764     {"help", no_argument, nullptr, 'h'},
765     {"user-id", required_argument, nullptr, 'u'},
766     {nullptr, 0, nullptr, 0},
767 };
768 
769 const std::string SHORT_OPTIONS_GET_UID_BY_BUNDLENAME = "hn:u:a:";
770 const struct option LONG_OPTIONS_GET_UID_BY_BUNDLENAME[] = {
771     {"help", no_argument, nullptr, 'h'},
772     {"bundle-name", required_argument, nullptr, 'n'},
773     {"user-id", required_argument, nullptr, 'u'},
774     {"app-index", required_argument, nullptr, 'a'},
775     {nullptr, 0, nullptr, 0},
776 };
777 
778 const std::string SHORT_OPTIONS_MIME = "ha:e:m:n:t:";
779 const struct option LONG_OPTIONS_MIME[] = {
780     {"help", no_argument, nullptr, 'h'},
781     {"ability-name", required_argument, nullptr, 'a'},
782     {"ext-name", required_argument, nullptr, 'e'},
783     {"module-name", required_argument, nullptr, 'm'},
784     {"bundle-name", required_argument, nullptr, 'n'},
785     {"mime-type", required_argument, nullptr, 't'},
786     {nullptr, 0, nullptr, 0},
787 };
788 
789 const std::string SHORT_OPTIONS_GET_GROUP_DIR = "hd:";
790 const struct option LONG_OPTIONS_GET_GROUP_DIR[] = {
791     {"help", no_argument, nullptr, 'h'},
792     {"data-group-id", required_argument, nullptr, 'd'},
793     {nullptr, 0, nullptr, 0},
794 };
795 
796 const std::string SHORT_OPTIONS_GET_JSON_PROFILE = "hp:n:m:u:";
797 const struct option LONG_OPTIONS_GET_JSON_PROFILE[] = {
798     {"help", no_argument, nullptr, 'h'},
799     {"profile-type", required_argument, nullptr, 'p'},
800     {"bundle-name", required_argument, nullptr, 'n'},
801     {"module-name", required_argument, nullptr, 'm'},
802     {"user-id", required_argument, nullptr, 'u'},
803     {nullptr, 0, nullptr, 0},
804 };
805 
806 const std::string SHORT_OPTIONS_UNINSTALLED_BUNDLE_INFO = "hn:";
807 const struct option LONG_OPTIONS_UNINSTALLED_BUNDLE_INFO[] = {
808     {"help", no_argument, nullptr, 'h'},
809     {"bundle-name", required_argument, nullptr, 'n'},
810     {nullptr, 0, nullptr, 0},
811 };
812 
813 const std::string SHORT_OPTIONS_GET_ODID = "hu:";
814 const struct option LONG_OPTIONS_GET_ODID[] = {
815     {"help", no_argument, nullptr, 'h'},
816     {"uid", required_argument, nullptr, 'u'},
817 };
818 
819 const std::string SHORT_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO = "hn:a:e:u:t:";
820 const struct option LONG_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO[] = {
821     {"help", no_argument, nullptr, 'h'},
822     {"bundle-name", required_argument, nullptr, 'n'},
823     {"action", required_argument, nullptr, 'a'},
824     {"entity", required_argument, nullptr, 'e'},
825     {"uri", required_argument, nullptr, 'u'},
826     {"type", required_argument, nullptr, 't'},
827     {nullptr, 0, nullptr, 0},
828 };
829 
830 const std::string SHORT_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE = "hn:c:u:";
831 const struct option LONG_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE[] = {
832     {"help", no_argument, nullptr, 'h'},
833     {"bundle-name", required_argument, nullptr, 'n'},
834     {"continueType", required_argument, nullptr, 'c'},
835     {"userId", required_argument, nullptr, 'u'},
836     {nullptr, 0, nullptr, 0},
837 };
838 }  // namespace
839 
BundleEventCallbackImpl()840 BundleEventCallbackImpl::BundleEventCallbackImpl()
841 {
842     APP_LOGI("create BundleEventCallbackImpl");
843 }
844 
~BundleEventCallbackImpl()845 BundleEventCallbackImpl::~BundleEventCallbackImpl()
846 {
847     APP_LOGI("destroy BundleEventCallbackImpl");
848 }
849 
OnReceiveEvent(const EventFwk::CommonEventData eventData)850 void BundleEventCallbackImpl::OnReceiveEvent(const EventFwk::CommonEventData eventData)
851 {
852     const Want &want = eventData.GetWant();
853     std::string bundleName = want.GetElement().GetBundleName();
854     std::string moduleName = want.GetElement().GetModuleName();
855     APP_LOGI("OnReceiveEvent, bundleName:%{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
856 }
857 
BundleTestTool(int argc,char * argv[])858 BundleTestTool::BundleTestTool(int argc, char *argv[]) : ShellCommand(argc, argv, TOOL_NAME)
859 {}
860 
~BundleTestTool()861 BundleTestTool::~BundleTestTool()
862 {}
863 
CreateCommandMap()864 ErrCode BundleTestTool::CreateCommandMap()
865 {
866     commandMap_ = {
867         {"help", std::bind(&BundleTestTool::RunAsHelpCommand, this)},
868         {"check", std::bind(&BundleTestTool::RunAsCheckCommand, this)},
869         {"setrm", std::bind(&BundleTestTool::RunAsSetRemovableCommand, this)},
870         {"getrm", std::bind(&BundleTestTool::RunAsGetRemovableCommand, this)},
871         {"installSandbox", std::bind(&BundleTestTool::RunAsInstallSandboxCommand, this)},
872         {"uninstallSandbox", std::bind(&BundleTestTool::RunAsUninstallSandboxCommand, this)},
873         {"dumpSandbox", std::bind(&BundleTestTool::RunAsDumpSandboxCommand, this)},
874         {"getStr", std::bind(&BundleTestTool::RunAsGetStringCommand, this)},
875         {"getIcon", std::bind(&BundleTestTool::RunAsGetIconCommand, this)},
876         {"addAppInstallRule", std::bind(&BundleTestTool::RunAsAddInstallRuleCommand, this)},
877         {"getAppInstallRule", std::bind(&BundleTestTool::RunAsGetInstallRuleCommand, this)},
878         {"deleteAppInstallRule", std::bind(&BundleTestTool::RunAsDeleteInstallRuleCommand, this)},
879         {"cleanAppInstallRule", std::bind(&BundleTestTool::RunAsCleanInstallRuleCommand, this)},
880         {"addAppRunningRule", std::bind(&BundleTestTool::RunAsAddAppRunningRuleCommand, this)},
881         {"deleteAppRunningRule", std::bind(&BundleTestTool::RunAsDeleteAppRunningRuleCommand, this)},
882         {"cleanAppRunningRule", std::bind(&BundleTestTool::RunAsCleanAppRunningRuleCommand, this)},
883         {"getAppRunningControlRule", std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleCommand, this)},
884         {"getAppRunningControlRuleResult",
885             std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleResultCommand, this)},
886         {"deployQuickFix", std::bind(&BundleTestTool::RunAsDeployQuickFix, this)},
887         {"switchQuickFix", std::bind(&BundleTestTool::RunAsSwitchQuickFix, this)},
888         {"deleteQuickFix", std::bind(&BundleTestTool::RunAsDeleteQuickFix, this)},
889         {"setDebugMode", std::bind(&BundleTestTool::RunAsSetDebugMode, this)},
890         {"getBundleStats", std::bind(&BundleTestTool::RunAsGetBundleStats, this)},
891         {"getAppProvisionInfo", std::bind(&BundleTestTool::RunAsGetAppProvisionInfo, this)},
892         {"getDistributedBundleName", std::bind(&BundleTestTool::RunAsGetDistributedBundleName, this)},
893         {"eventCB", std::bind(&BundleTestTool::HandleBundleEventCallback, this)},
894         {"resetAOTCompileStatus", std::bind(&BundleTestTool::ResetAOTCompileStatus, this)},
895         {"sendCommonEvent", std::bind(&BundleTestTool::SendCommonEvent, this)},
896         {"getProxyDataInfos", std::bind(&BundleTestTool::RunAsGetProxyDataCommand, this)},
897         {"getAllProxyDataInfos", std::bind(&BundleTestTool::RunAsGetAllProxyDataCommand, this)},
898         {"setExtNameOrMimeToApp", std::bind(&BundleTestTool::RunAsSetExtNameOrMIMEToAppCommand, this)},
899         {"delExtNameOrMimeToApp", std::bind(&BundleTestTool::RunAsDelExtNameOrMIMEToAppCommand, this)},
900         {"queryDataGroupInfos", std::bind(&BundleTestTool::RunAsQueryDataGroupInfos, this)},
901         {"getGroupDir", std::bind(&BundleTestTool::RunAsGetGroupDir, this)},
902         {"getJsonProfile", std::bind(&BundleTestTool::RunAsGetJsonProfile, this)},
903         {"getUninstalledBundleInfo", std::bind(&BundleTestTool::RunAsGetUninstalledBundleInfo, this)},
904         {"getOdid", std::bind(&BundleTestTool::RunAsGetOdid, this)},
905         {"getUidByBundleName", std::bind(&BundleTestTool::RunGetUidByBundleName, this)},
906         {"implicitQuerySkillUriInfo",
907             std::bind(&BundleTestTool::RunAsImplicitQuerySkillUriInfo, this)},
908         {"queryAbilityInfoByContinueType",
909             std::bind(&BundleTestTool::RunAsQueryAbilityInfoByContinueType, this)},
910         {"cleanBundleCacheFilesAutomatic",
911             std::bind(&BundleTestTool::RunAsCleanBundleCacheFilesAutomaticCommand, this)},
912         {"getContinueBundleName",
913             std::bind(&BundleTestTool::RunAsGetContinueBundleName, this)},
914         {"getBundleNameByAppId",
915             std::bind(&BundleTestTool::RunAsGetBundleNameByAppId, this)}
916     };
917 
918     return OHOS::ERR_OK;
919 }
920 
CreateMessageMap()921 ErrCode BundleTestTool::CreateMessageMap()
922 {
923     messageMap_ = BundleCommandCommon::bundleMessageMap_;
924 
925     return OHOS::ERR_OK;
926 }
927 
Init()928 ErrCode BundleTestTool::Init()
929 {
930     APP_LOGI("BundleTestTool Init()");
931     ErrCode result = OHOS::ERR_OK;
932     if (bundleMgrProxy_ == nullptr) {
933         bundleMgrProxy_ = BundleCommandCommon::GetBundleMgrProxy();
934         if (bundleMgrProxy_ != nullptr) {
935             if (bundleInstallerProxy_ == nullptr) {
936                 bundleInstallerProxy_ = bundleMgrProxy_->GetBundleInstaller();
937             }
938         }
939     }
940 
941     if ((bundleMgrProxy_ == nullptr) || (bundleInstallerProxy_ == nullptr) ||
942         (bundleInstallerProxy_->AsObject() == nullptr)) {
943         result = OHOS::ERR_INVALID_VALUE;
944     }
945 
946 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
947     if (distributedBmsProxy_ == nullptr) {
948         distributedBmsProxy_ = BundleCommandCommon::GetDistributedBundleMgrService();
949     }
950 #endif
951 
952     return result;
953 }
954 
CreateQuickFixMsgMap(std::unordered_map<int32_t,std::string> & quickFixMsgMap)955 void BundleTestTool::CreateQuickFixMsgMap(std::unordered_map<int32_t, std::string> &quickFixMsgMap)
956 {
957     quickFixMsgMap = {
958         { ERR_OK, Constants::EMPTY_STRING },
959         { ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR },
960         { ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR },
961         { ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED },
962         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME },
963         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME },
964         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME },
965         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME,
966             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME },
967         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME,
968             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME },
969         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME },
970         { ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE },
971         { ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE },
972         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST },
973         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST },
974         { ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME,
975             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME },
976         { ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED,
977             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED },
978         { ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED,
979             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED },
980         { ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED },
981         { ERR_APPEXECFWK_OPERATION_TIME_OUT, MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT },
982         { ERR_APPEXECFWK_FAILED_SERVICE_DIED, MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED },
983         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE,
984             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE },
985         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED },
986         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED,
987             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED },
988         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME },
989         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO,
990             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO },
991         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM },
992         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR },
993         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR },
994         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR,
995             MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR },
996         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED },
997         { ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED },
998         { ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED,
999             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED },
1000         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR },
1001         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE },
1002         { ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS },
1003         { ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO,
1004             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO },
1005         { ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED,
1006             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED },
1007         { ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED,
1008             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED },
1009         { ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED,
1010             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED },
1011         { ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB,
1012             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB },
1013         { ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED,
1014             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED }
1015     };
1016 }
1017 
RunAsHelpCommand()1018 ErrCode BundleTestTool::RunAsHelpCommand()
1019 {
1020     resultReceiver_.append(HELP_MSG);
1021 
1022     return OHOS::ERR_OK;
1023 }
1024 
CheckOperation(int userId,std::string deviceId,std::string bundleName,std::string moduleName,std::string abilityName)1025 ErrCode BundleTestTool::CheckOperation(int userId, std::string deviceId, std::string bundleName,
1026     std::string moduleName, std::string abilityName)
1027 {
1028     std::unique_lock<std::mutex> lock(mutex_);
1029     sptr<BundleToolCallbackStub> bundleToolCallbackStub =
1030         new(std::nothrow) BundleToolCallbackStub(cv_, mutex_, dataReady_);
1031     if (bundleToolCallbackStub == nullptr) {
1032         APP_LOGE("bundleToolCallbackStub is null");
1033         return OHOS::ERR_INVALID_VALUE;
1034     }
1035     APP_LOGI("CheckAbilityEnableInstall param: userId:%{public}d, bundleName:%{public}s, moduleName:%{public}s," \
1036         "abilityName:%{public}s", userId, bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
1037     AAFwk::Want want;
1038     want.SetElementName(deviceId, bundleName, abilityName, moduleName);
1039     bool ret = bundleMgrProxy_->CheckAbilityEnableInstall(want, 1, userId, bundleToolCallbackStub);
1040     if (!ret) {
1041         APP_LOGE("CheckAbilityEnableInstall failed");
1042         return OHOS::ERR_OK;
1043     }
1044     APP_LOGI("CheckAbilityEnableInstall wait");
1045     cv_.wait(lock, [this] { return dataReady_; });
1046     dataReady_ = false;
1047     return OHOS::ERR_OK;
1048 }
1049 
RunAsCheckCommand()1050 ErrCode BundleTestTool::RunAsCheckCommand()
1051 {
1052     int counter = 0;
1053     int userId = 100;
1054     std::string deviceId = "";
1055     std::string bundleName = "";
1056     std::string moduleName = "";
1057     std::string abilityName = "";
1058     while (true) {
1059         counter++;
1060         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1061         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1062         if (optind < 0 || optind > argc_) {
1063             return OHOS::ERR_INVALID_VALUE;
1064         }
1065         if (option == -1) {
1066             // When scanning the first argument
1067             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1068                 // 'CheckAbilityEnableInstall' with no option: CheckAbilityEnableInstall
1069                 // 'CheckAbilityEnableInstall' with a wrong argument: CheckAbilityEnableInstall
1070                 APP_LOGD("'CheckAbilityEnableInstall' with no option.");
1071                 return OHOS::ERR_INVALID_VALUE;
1072             }
1073             break;
1074         }
1075         switch (option) {
1076             case 'n': {
1077                 bundleName = optarg;
1078                 break;
1079             }
1080             case 'm': {
1081                 moduleName = optarg;
1082                 break;
1083             }
1084             case 'a': {
1085                 abilityName = optarg;
1086                 break;
1087             }
1088             case 'd': {
1089                 deviceId = optarg;
1090                 break;
1091             }
1092             case 'u': {
1093                 userId = std::stoi(optarg);
1094                 break;
1095             }
1096             default: {
1097                 return OHOS::ERR_INVALID_VALUE;
1098             }
1099         }
1100     }
1101     return CheckOperation(userId, deviceId, bundleName, moduleName, abilityName);
1102 }
1103 
SetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,int isRemovable) const1104 bool BundleTestTool::SetIsRemovableOperation(
1105     const std::string &bundleName, const std::string &moduleName, int isRemovable) const
1106 {
1107     bool enable = true;
1108     if (isRemovable == 0) {
1109         enable = false;
1110     }
1111     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s, enable:%{public}d", bundleName.c_str(), moduleName.c_str(),
1112         enable);
1113     auto ret = bundleMgrProxy_->SetModuleRemovable(bundleName, moduleName, enable);
1114     APP_LOGD("SetModuleRemovable end bundleName: %{public}d", ret);
1115     if (!ret) {
1116         APP_LOGE("SetIsRemovableOperation failed");
1117         return false;
1118     }
1119     return ret;
1120 }
1121 
GetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,std::string & result) const1122 bool BundleTestTool::GetIsRemovableOperation(
1123     const std::string &bundleName, const std::string &moduleName, std::string &result) const
1124 {
1125     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
1126     bool isRemovable = false;
1127     auto ret = bundleMgrProxy_->IsModuleRemovable(bundleName, moduleName, isRemovable);
1128     APP_LOGD("IsModuleRemovable end bundleName: %{public}s, isRemovable:%{public}d", bundleName.c_str(), isRemovable);
1129     result.append("isRemovable: " + std::to_string(isRemovable) + "\n");
1130     if (ret != ERR_OK) {
1131         APP_LOGE("IsModuleRemovable failed, ret: %{public}d", ret);
1132         return false;
1133     }
1134     return true;
1135 }
1136 
CheckRemovableErrorOption(int option,int counter,const std::string & commandName)1137 bool BundleTestTool::CheckRemovableErrorOption(int option, int counter, const std::string &commandName)
1138 {
1139     if (option == -1) {
1140         if (counter == 1) {
1141             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
1142                 // 'bundle_test_tool setrm/getrm' with no option: bundle_test_tool setrm/getrm
1143                 // 'bundle_test_tool setrm/getrm' with a wrong argument: bundle_test_tool setrm/getrm xxx
1144                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
1145                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
1146                 return false;
1147             }
1148         }
1149         return true;
1150     } else if (option == '?') {
1151         switch (optopt) {
1152             case 'i': {
1153                 if (commandName == GET_RM) {
1154                     std::string unknownOption = "";
1155                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1156                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1157                     resultReceiver_.append(unknownOptionMsg);
1158                 } else {
1159                     APP_LOGD("'bundle_test_tool %{public}s -i' with no argument.", commandName.c_str());
1160                     resultReceiver_.append("error: -i option requires a value.\n");
1161                 }
1162                 break;
1163             }
1164             case 'm': {
1165                 APP_LOGD("'bundle_test_tool %{public}s -m' with no argument.", commandName.c_str());
1166                 resultReceiver_.append("error: -m option requires a value.\n");
1167                 break;
1168             }
1169             case 'n': {
1170                 APP_LOGD("'bundle_test_tool %{public}s -n' with no argument.", commandName.c_str());
1171                 resultReceiver_.append("error: -n option requires a value.\n");
1172                 break;
1173             }
1174             default: {
1175                 std::string unknownOption = "";
1176                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1177                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1178                 resultReceiver_.append(unknownOptionMsg);
1179                 break;
1180             }
1181         }
1182     }
1183     return false;
1184 }
1185 
CheckRemovableCorrectOption(int option,const std::string & commandName,int & isRemovable,std::string & name)1186 bool BundleTestTool::CheckRemovableCorrectOption(
1187     int option, const std::string &commandName, int &isRemovable, std::string &name)
1188 {
1189     bool ret = true;
1190     switch (option) {
1191         case 'h': {
1192             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1193             ret = false;
1194             break;
1195         }
1196         case 'n': {
1197             name = optarg;
1198             APP_LOGD("'bundle_test_tool %{public}s -n %{public}s'", commandName.c_str(), argv_[optind - 1]);
1199             break;
1200         }
1201         case 'i': {
1202             if (commandName == GET_RM) {
1203                 std::string unknownOption = "";
1204                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1205                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1206                 resultReceiver_.append(unknownOptionMsg);
1207                 ret = false;
1208             } else if (OHOS::StrToInt(optarg, isRemovable)) {
1209                 APP_LOGD("'bundle_test_tool %{public}s -i isRemovable:%{public}d, %{public}s'",
1210                     commandName.c_str(), isRemovable, argv_[optind - 1]);
1211             } else {
1212                 APP_LOGE("bundle_test_tool setrm with error %{private}s", optarg);
1213                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1214                 ret = false;
1215             }
1216             break;
1217         }
1218         case 'm': {
1219             name = optarg;
1220             APP_LOGD("'bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s'",
1221                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1222             break;
1223         }
1224         default: {
1225             std::string unknownOption = "";
1226             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1227             APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1228             resultReceiver_.append(unknownOptionMsg);
1229             ret = false;
1230             break;
1231         }
1232     }
1233     return ret;
1234 }
1235 
RunAsSetRemovableCommand()1236 ErrCode BundleTestTool::RunAsSetRemovableCommand()
1237 {
1238     int result = OHOS::ERR_OK;
1239     int counter = 0;
1240     int isRemovable = 0;
1241     std::string commandName = SET_RM;
1242     std::string name = "";
1243     std::string bundleName = "";
1244     std::string moduleName = "";
1245     APP_LOGD("RunAsSetCommand is start");
1246     while (true) {
1247         counter++;
1248         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1249         if (optind < 0 || optind > argc_) {
1250             return OHOS::ERR_INVALID_VALUE;
1251         }
1252         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d, argv_[optind - 1]:%{public}s", option,
1253             optopt, optind, argv_[optind - 1]);
1254         if (option == -1 || option == '?') {
1255             result = !CheckRemovableErrorOption(option, counter, commandName)? OHOS::ERR_INVALID_VALUE : result;
1256             break;
1257         }
1258         result = !CheckRemovableCorrectOption(option, commandName, isRemovable, name)
1259             ? OHOS::ERR_INVALID_VALUE : result;
1260         moduleName = option == 'm' ? name : moduleName;
1261         bundleName = option == 'n' ? name : bundleName;
1262     }
1263     if (result == OHOS::ERR_OK) {
1264         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
1265             APP_LOGD("'bundle_test_tool setrm' with not enough option.");
1266             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
1267             result = OHOS::ERR_INVALID_VALUE;
1268         }
1269     }
1270     if (result != OHOS::ERR_OK) {
1271         resultReceiver_.append(HELP_MSG_SET);
1272     } else {
1273         bool setResult = false;
1274         setResult = SetIsRemovableOperation(bundleName, moduleName, isRemovable);
1275         APP_LOGD("'bundle_test_tool setrm' isRemovable is %{public}d", isRemovable);
1276         resultReceiver_ = setResult ? STRING_SET_REMOVABLE_OK : STRING_SET_REMOVABLE_NG;
1277     }
1278     return result;
1279 }
1280 
RunAsGetRemovableCommand()1281 ErrCode BundleTestTool::RunAsGetRemovableCommand()
1282 {
1283     int result = OHOS::ERR_OK;
1284     int counter = 0;
1285     std::string commandName = GET_RM;
1286     std::string name = "";
1287     std::string bundleName = "";
1288     std::string moduleName = "";
1289     APP_LOGD("RunAsGetRemovableCommand is start");
1290     while (true) {
1291         counter++;
1292         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1293         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1294         if (optind < 0 || optind > argc_) {
1295             return OHOS::ERR_INVALID_VALUE;
1296         }
1297         if (option == -1 || option == '?') {
1298             result = !CheckRemovableErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1299             break;
1300         }
1301         int tempIsRem = 0;
1302         result = !CheckRemovableCorrectOption(option, commandName, tempIsRem, name)
1303             ? OHOS::ERR_INVALID_VALUE : result;
1304         moduleName = option == 'm' ? name : moduleName;
1305         bundleName = option == 'n' ? name : bundleName;
1306     }
1307 
1308     if (result == OHOS::ERR_OK) {
1309         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
1310             APP_LOGD("'bundle_test_tool getrm' with no option.");
1311             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
1312             result = OHOS::ERR_INVALID_VALUE;
1313         }
1314     }
1315 
1316     if (result != OHOS::ERR_OK) {
1317         resultReceiver_.append(HELP_MSG_GET_REMOVABLE);
1318     } else {
1319         std::string results = "";
1320         GetIsRemovableOperation(bundleName, moduleName, results);
1321         if (results.empty()) {
1322             resultReceiver_.append(STRING_GET_REMOVABLE_NG);
1323             return result;
1324         }
1325         resultReceiver_.append(results);
1326     }
1327     return result;
1328 }
1329 
CheckSandboxErrorOption(int option,int counter,const std::string & commandName)1330 bool BundleTestTool::CheckSandboxErrorOption(int option, int counter, const std::string &commandName)
1331 {
1332     if (option == -1) {
1333         if (counter == 1) {
1334             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
1335                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
1336                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
1337                 return false;
1338             }
1339         }
1340         return true;
1341     } else if (option == '?') {
1342         switch (optopt) {
1343             case 'n':
1344             case 'u':
1345             case 'd':
1346             case 'a': {
1347                 if ((commandName != INSTALL_SANDBOX && optopt == 'd') ||
1348                     (commandName == INSTALL_SANDBOX && optopt == 'a')) {
1349                     std::string unknownOption = "";
1350                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1351                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1352                     resultReceiver_.append(unknownOptionMsg);
1353                     break;
1354                 }
1355                 APP_LOGD("'bundle_test_tool %{public}s' -%{public}c with no argument.", commandName.c_str(), optopt);
1356                 resultReceiver_.append("error: option requires a value.\n");
1357                 break;
1358             }
1359             default: {
1360                 std::string unknownOption = "";
1361                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1362                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1363                 resultReceiver_.append(unknownOptionMsg);
1364                 break;
1365             }
1366         }
1367     }
1368     return false;
1369 }
1370 
CheckSandboxCorrectOption(int option,const std::string & commandName,int & data,std::string & bundleName)1371 bool BundleTestTool::CheckSandboxCorrectOption(
1372     int option, const std::string &commandName, int &data, std::string &bundleName)
1373 {
1374     bool ret = true;
1375     switch (option) {
1376         case 'h': {
1377             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1378             ret = false;
1379             break;
1380         }
1381         case 'n': {
1382             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1383             bundleName = optarg;
1384             break;
1385         }
1386         case 'u':
1387         case 'a':
1388         case 'd': {
1389             if ((commandName != INSTALL_SANDBOX && option == 'd') ||
1390                 (commandName == INSTALL_SANDBOX && option == 'a')) {
1391                 std::string unknownOption = "";
1392                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1393                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1394                 resultReceiver_.append(unknownOptionMsg);
1395                 ret = false;
1396                 break;
1397             }
1398 
1399             APP_LOGD("'bundle_test_tool %{public}s %{public}s %{public}s'", commandName.c_str(),
1400                 argv_[optind - OFFSET_REQUIRED_ARGUMENT], optarg);
1401 
1402             if (!OHOS::StrToInt(optarg, data)) {
1403                 if (option == 'u') {
1404                     APP_LOGE("bundle_test_tool %{public}s with error -u %{private}s", commandName.c_str(), optarg);
1405                 } else if (option == 'a') {
1406                     APP_LOGE("bundle_test_tool %{public}s with error -a %{private}s", commandName.c_str(), optarg);
1407                 } else {
1408                     APP_LOGE("bundle_test_tool %{public}s with error -d %{private}s", commandName.c_str(), optarg);
1409                 }
1410                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1411                 ret = false;
1412             }
1413             break;
1414         }
1415         default: {
1416             ret = false;
1417             break;
1418         }
1419     }
1420     return ret;
1421 }
1422 
InstallSandboxOperation(const std::string & bundleName,const int32_t userId,const int32_t dlpType,int32_t & appIndex) const1423 ErrCode BundleTestTool::InstallSandboxOperation(
1424     const std::string &bundleName, const int32_t userId, const int32_t dlpType, int32_t &appIndex) const
1425 {
1426     APP_LOGD("InstallSandboxOperation of bundleName %{public}s, dipType is %{public}d", bundleName.c_str(), dlpType);
1427     return bundleInstallerProxy_->InstallSandboxApp(bundleName, dlpType, userId, appIndex);
1428 }
1429 
RunAsInstallSandboxCommand()1430 ErrCode BundleTestTool::RunAsInstallSandboxCommand()
1431 {
1432     int result = OHOS::ERR_OK;
1433     int counter = 0;
1434     std::string commandName = INSTALL_SANDBOX;
1435     std::string bundleName = "";
1436     int32_t userId = 100;
1437     int32_t dlpType = 0;
1438     while (true) {
1439         counter++;
1440         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1441         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1442         if (optind < 0 || optind > argc_) {
1443             return OHOS::ERR_INVALID_VALUE;
1444         }
1445         if (option == -1 || option == '?') {
1446             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1447             break;
1448         } else if (option == 'u') {
1449             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1450                 OHOS::ERR_INVALID_VALUE : result;
1451         } else {
1452             result = !CheckSandboxCorrectOption(option, commandName, dlpType, bundleName) ?
1453                 OHOS::ERR_INVALID_VALUE : result;
1454         }
1455     }
1456 
1457     if (result == OHOS::ERR_OK && bundleName == "") {
1458         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1459         result = OHOS::ERR_INVALID_VALUE;
1460     } else {
1461         APP_LOGD("installSandbox app bundleName is %{public}s", bundleName.c_str());
1462     }
1463 
1464     if (result != OHOS::ERR_OK) {
1465         resultReceiver_.append(HELP_MSG_INSTALL_SANDBOX);
1466         return result;
1467     }
1468 
1469     int32_t appIndex = 0;
1470     auto ret = InstallSandboxOperation(bundleName, userId, dlpType, appIndex);
1471     if (ret == OHOS::ERR_OK) {
1472         resultReceiver_.append(STRING_INSTALL_SANDBOX_SUCCESSFULLY);
1473     } else {
1474         resultReceiver_.append(STRING_INSTALL_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1475     }
1476     return result;
1477 }
1478 
UninstallSandboxOperation(const std::string & bundleName,const int32_t appIndex,const int32_t userId) const1479 ErrCode BundleTestTool::UninstallSandboxOperation(const std::string &bundleName,
1480     const int32_t appIndex, const int32_t userId) const
1481 {
1482     APP_LOGD("UninstallSandboxOperation of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1483     return bundleInstallerProxy_->UninstallSandboxApp(bundleName, appIndex, userId);
1484 }
1485 
RunAsUninstallSandboxCommand()1486 ErrCode BundleTestTool::RunAsUninstallSandboxCommand()
1487 {
1488     int result = OHOS::ERR_OK;
1489     int counter = 0;
1490     std::string bundleName = "";
1491     std::string commandName = UNINSTALL_SANDBOX;
1492     int32_t userId = 100;
1493     int32_t appIndex = -1;
1494     while (true) {
1495         counter++;
1496         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1497         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1498         if (optind < 0 || optind > argc_) {
1499             return OHOS::ERR_INVALID_VALUE;
1500         }
1501 
1502         if (option == -1 || option == '?') {
1503             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1504             break;
1505         } else if (option == 'u') {
1506             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1507                 OHOS::ERR_INVALID_VALUE : result;
1508         } else {
1509             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1510                 OHOS::ERR_INVALID_VALUE : result;
1511         }
1512     }
1513 
1514     if (result == OHOS::ERR_OK && bundleName == "") {
1515         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1516         result = OHOS::ERR_INVALID_VALUE;
1517     } else {
1518         APP_LOGD("uninstallSandbox app bundleName is %{private}s", bundleName.c_str());
1519     }
1520 
1521     if (result != OHOS::ERR_OK) {
1522         resultReceiver_.append(HELP_MSG_UNINSTALL_SANDBOX);
1523         return result;
1524     }
1525 
1526     auto ret = UninstallSandboxOperation(bundleName, appIndex, userId);
1527     if (ret == ERR_OK) {
1528         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_SUCCESSFULLY);
1529     } else {
1530         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_FAILED + "errCode is " + std::to_string(ret) + "\n");
1531     }
1532     return result;
1533 }
1534 
DumpSandboxBundleInfo(const std::string & bundleName,const int32_t appIndex,const int32_t userId,std::string & dumpResults)1535 ErrCode BundleTestTool::DumpSandboxBundleInfo(const std::string &bundleName, const int32_t appIndex,
1536     const int32_t userId, std::string &dumpResults)
1537 {
1538     APP_LOGD("DumpSandboxBundleInfo of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1539     BundleInfo bundleInfo;
1540     BundleMgrClient client;
1541     auto dumpRet = client.GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo);
1542     if (dumpRet == ERR_OK) {
1543         nlohmann::json jsonObject = bundleInfo;
1544         jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
1545         dumpResults= jsonObject.dump(Constants::DUMP_INDENT);
1546     }
1547     return dumpRet;
1548 }
1549 
RunAsDumpSandboxCommand()1550 ErrCode BundleTestTool::RunAsDumpSandboxCommand()
1551 {
1552     int result = OHOS::ERR_OK;
1553     int counter = 0;
1554     std::string bundleName = "";
1555     std::string commandName = DUMP_SANDBOX;
1556     int32_t userId = 100;
1557     int32_t appIndex = -1;
1558     while (true) {
1559         counter++;
1560         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1561         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1562         if (optind < 0 || optind > argc_) {
1563             return OHOS::ERR_INVALID_VALUE;
1564         }
1565         if (option == -1 || option == '?') {
1566             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1567             break;
1568         } else if (option == 'u') {
1569             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1570                 OHOS::ERR_INVALID_VALUE : result;
1571         } else {
1572             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1573                 OHOS::ERR_INVALID_VALUE : result;
1574         }
1575     }
1576 
1577     if (result == OHOS::ERR_OK && bundleName == "") {
1578         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1579         result = OHOS::ERR_INVALID_VALUE;
1580     } else {
1581         APP_LOGD("dumpSandbox app bundleName is %{public}s", bundleName.c_str());
1582     }
1583 
1584     if (result != OHOS::ERR_OK) {
1585         resultReceiver_.append(HELP_MSG_DUMP_SANDBOX);
1586         return result;
1587     }
1588 
1589     std::string dumpRes = "";
1590     ErrCode ret = DumpSandboxBundleInfo(bundleName, appIndex, userId, dumpRes);
1591     if (ret == ERR_OK) {
1592         resultReceiver_.append(dumpRes + "\n");
1593     } else {
1594         resultReceiver_.append(STRING_DUMP_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1595     }
1596     return result;
1597 }
1598 
StringToInt(std::string optarg,const std::string & commandName,int & temp,bool & result)1599 ErrCode BundleTestTool::StringToInt(
1600     std::string optarg, const std::string &commandName, int &temp, bool &result)
1601 {
1602     try {
1603         temp = std::stoi(optarg);
1604         if (optind > 0 && optind <= argc_) {
1605             APP_LOGD("bundle_test_tool %{public}s -u user-id:%{public}d, %{public}s",
1606                 commandName.c_str(), temp, argv_[optind - 1]);
1607         }
1608     } catch (const std::exception& e) {
1609         std::cerr << e.what() << std::endl;
1610         result = false;
1611     }
1612     return OHOS::ERR_OK;
1613 }
1614 
StringToUnsignedLongLong(std::string optarg,const std::string & commandName,uint64_t & temp,bool & result)1615 ErrCode BundleTestTool::StringToUnsignedLongLong(
1616     std::string optarg, const std::string &commandName, uint64_t &temp, bool &result)
1617 {
1618     try {
1619         APP_LOGI("StringToUnsignedLongLong start, optarg : %{public}s", optarg.c_str());
1620         if ((optarg == "") || (optarg[0] == '0') || (!isdigit(optarg[0]))) {
1621             resultReceiver_.append("error: parameter error, cache size must be greater than 0\n");
1622             return OHOS::ERR_INVALID_VALUE;
1623         }
1624         temp = std::stoull(optarg);
1625     } catch (const std::exception& e) {
1626         std::cerr << e.what() << std::endl;
1627         result = false;
1628     }
1629     return OHOS::ERR_OK;
1630 }
1631 
HandleUnknownOption(const std::string & commandName,bool & ret)1632 bool BundleTestTool::HandleUnknownOption(const std::string &commandName, bool &ret)
1633 {
1634     std::string unknownOption = "";
1635     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1636     APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1637     resultReceiver_.append(unknownOptionMsg);
1638     return ret = false;
1639 }
1640 
CheckGetStringCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1641 bool BundleTestTool::CheckGetStringCorrectOption(
1642     int option, const std::string &commandName, int &temp, std::string &name)
1643 {
1644     bool ret = true;
1645     switch (option) {
1646         case 'h': {
1647             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1648             ret = false;
1649             break;
1650         }
1651         case 'n': {
1652             name = optarg;
1653             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1654             break;
1655         }
1656         case 'm': {
1657             name = optarg;
1658             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1659                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1660             break;
1661         }
1662         case 'c': {
1663             name = optarg;
1664             APP_LOGD("bundle_test_tool %{public}s -m continue-type:%{public}s, %{public}s",
1665                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1666             break;
1667         }
1668         case 'u': {
1669             StringToInt(optarg, commandName, temp, ret);
1670             break;
1671         }
1672         case 'a': {
1673             StringToInt(optarg, commandName, temp, ret);
1674             break;
1675         }
1676         case 'p': {
1677             StringToInt(optarg, commandName, temp, ret);
1678             break;
1679         }
1680         case 'i': {
1681             StringToInt(optarg, commandName, temp, ret);
1682             break;
1683         }
1684         default: {
1685             HandleUnknownOption(commandName, ret);
1686             break;
1687         }
1688     }
1689     return ret;
1690 }
1691 
CheckGetProxyDataCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1692 bool BundleTestTool::CheckGetProxyDataCorrectOption(
1693     int option, const std::string &commandName, int &temp, std::string &name)
1694 {
1695     bool ret = true;
1696     switch (option) {
1697         case 'h': {
1698             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1699             ret = false;
1700             break;
1701         }
1702         case 'n': {
1703             name = optarg;
1704             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1705             break;
1706         }
1707         case 'm': {
1708             name = optarg;
1709             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1710                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
1711             break;
1712         }
1713         case 'u': {
1714             StringToInt(optarg, commandName, temp, ret);
1715             break;
1716         }
1717         default: {
1718             std::string unknownOption = "";
1719             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1720             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1721             resultReceiver_.append(unknownOptionMsg);
1722             ret = false;
1723             break;
1724         }
1725     }
1726     return ret;
1727 }
1728 
CheckGetAllProxyDataCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1729 bool BundleTestTool::CheckGetAllProxyDataCorrectOption(
1730     int option, const std::string &commandName, int &temp, std::string &name)
1731 {
1732     bool ret = true;
1733     switch (option) {
1734         case 'h': {
1735             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1736             ret = false;
1737             break;
1738         }
1739         case 'u': {
1740             StringToInt(optarg, commandName, temp, ret);
1741             break;
1742         }
1743         default: {
1744             std::string unknownOption = "";
1745             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1746             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1747             resultReceiver_.append(unknownOptionMsg);
1748             ret = false;
1749             break;
1750         }
1751     }
1752     return ret;
1753 }
1754 
RunAsGetProxyDataCommand()1755 ErrCode BundleTestTool::RunAsGetProxyDataCommand()
1756 {
1757     int result = OHOS::ERR_OK;
1758     int counter = 0;
1759     std::string commandName = "getProxyData";
1760     std::string name = "";
1761     std::string bundleName = "";
1762     std::string moduleName = "";
1763     int userId = Constants::ALL_USERID;
1764     APP_LOGD("RunAsGetProxyDataCommand is start");
1765     while (true) {
1766         counter++;
1767         int32_t option = getopt_long(
1768             argc_, argv_, SHORT_OPTIONS_PROXY_DATA.c_str(), LONG_OPTIONS_PROXY_DATA, nullptr);
1769         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1770         if (optind < 0 || optind > argc_) {
1771             return OHOS::ERR_INVALID_VALUE;
1772         }
1773         if (option == -1) {
1774             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1775                 APP_LOGD("bundle_test_tool getProxyData with no option.");
1776                 resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
1777                 return OHOS::ERR_INVALID_VALUE;
1778             }
1779             break;
1780         }
1781         int temp = 0;
1782         result = !CheckGetProxyDataCorrectOption(option, commandName, temp, name)
1783                  ? OHOS::ERR_INVALID_VALUE : result;
1784         moduleName = option == 'm' ? name : moduleName;
1785         bundleName = option == 'n' ? name : bundleName;
1786         userId = option == 'u' ? temp : userId;
1787     }
1788 
1789     if (result != OHOS::ERR_OK) {
1790         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
1791     } else {
1792         std::vector<ProxyData> proxyDatas;
1793         result = bundleMgrProxy_->GetProxyDataInfos(bundleName, moduleName, proxyDatas, userId);
1794         if (result == ERR_OK) {
1795             nlohmann::json jsonObject = proxyDatas;
1796             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
1797             resultReceiver_.append(results);
1798         } else {
1799             resultReceiver_.append(STRING_GET_PROXY_DATA_NG + " errCode is "+ std::to_string(result) + "\n");
1800         }
1801     }
1802     return result;
1803 }
1804 
RunAsGetAllProxyDataCommand()1805 ErrCode BundleTestTool::RunAsGetAllProxyDataCommand()
1806 {
1807     int result = OHOS::ERR_OK;
1808     int counter = 0;
1809     std::string commandName = "getProxyData";
1810     std::string name = "";
1811     int userId = Constants::ALL_USERID;
1812     APP_LOGD("RunAsGetAllProxyDataCommand is start");
1813     while (true) {
1814         counter++;
1815         int32_t option = getopt_long(
1816             argc_, argv_, SHORT_OPTIONS_ALL_PROXY_DATA.c_str(), LONG_OPTIONS_ALL_PROXY_DATA, nullptr);
1817         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1818         if (optind < 0 || optind > argc_) {
1819             return OHOS::ERR_INVALID_VALUE;
1820         }
1821         if (option == -1) {
1822             break;
1823         }
1824 
1825         int temp = 0;
1826         result = !CheckGetAllProxyDataCorrectOption(option, commandName, temp, name)
1827                  ? OHOS::ERR_INVALID_VALUE : result;
1828         userId = option == 'u' ? temp : userId;
1829     }
1830 
1831     if (result != OHOS::ERR_OK) {
1832         resultReceiver_.append(HELP_MSG_GET_ALL_PROXY_DATA);
1833     } else {
1834         std::vector<ProxyData> proxyDatas;
1835         result = bundleMgrProxy_->GetAllProxyDataInfos(proxyDatas, userId);
1836         if (result == ERR_OK) {
1837             nlohmann::json jsonObject = proxyDatas;
1838             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
1839             resultReceiver_.append(results);
1840         } else {
1841             resultReceiver_.append(STRING_GET_PROXY_DATA_NG + " errCode is "+ std::to_string(result) + "\n");
1842         }
1843     }
1844     return result;
1845 }
1846 
RunAsGetStringCommand()1847 ErrCode BundleTestTool::RunAsGetStringCommand()
1848 {
1849     int result = OHOS::ERR_OK;
1850     int counter = 0;
1851     std::string commandName = "getStr";
1852     std::string name = "";
1853     std::string bundleName = "";
1854     std::string moduleName = "";
1855     int userId = 100;
1856     int labelId = 0;
1857     APP_LOGD("RunAsGetStringCommand is start");
1858     while (true) {
1859         counter++;
1860         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
1861         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1862         if (optind < 0 || optind > argc_) {
1863             return OHOS::ERR_INVALID_VALUE;
1864         }
1865         if (option == -1) {
1866             // When scanning the first argument
1867             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1868                 // 'GetStringById' with no option: GetStringById
1869                 // 'GetStringById' with a wrong argument: GetStringById
1870                 APP_LOGD("bundle_test_tool getStr with no option.");
1871                 resultReceiver_.append(HELP_MSG_NO_GETSTRING_OPTION);
1872                 return OHOS::ERR_INVALID_VALUE;
1873             }
1874             break;
1875         }
1876         int temp = 0;
1877         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
1878             ? OHOS::ERR_INVALID_VALUE : result;
1879         moduleName = option == 'm' ? name : moduleName;
1880         bundleName = option == 'n' ? name : bundleName;
1881         userId = option == 'u' ? temp : userId;
1882         labelId = option == 'i' ? temp : labelId;
1883     }
1884 
1885     if (result != OHOS::ERR_OK) {
1886         resultReceiver_.append(HELP_MSG_GET_STRING);
1887     } else {
1888         std::string results = "";
1889         results = bundleMgrProxy_->GetStringById(bundleName, moduleName, labelId, userId);
1890         if (results.empty()) {
1891             resultReceiver_.append(STRING_GET_STRING_NG);
1892             return result;
1893         }
1894         resultReceiver_.append(results);
1895     }
1896     return result;
1897 }
1898 
CheckExtOrMimeCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1899 bool BundleTestTool::CheckExtOrMimeCorrectOption(
1900     int option, const std::string &commandName, int &temp, std::string &name)
1901 {
1902     bool ret = true;
1903     switch (option) {
1904         case 'h': {
1905             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1906             ret = false;
1907             break;
1908         }
1909         case 'n': {
1910             name = optarg;
1911             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1912             break;
1913         }
1914         case 'm': {
1915             name = optarg;
1916             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1917                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
1918             break;
1919         }
1920         case 'a': {
1921             name = optarg;
1922             APP_LOGD("bundle_test_tool %{public}s -m ability-name:%{public}s, %{public}s",
1923                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
1924             break;
1925         }
1926         case 'e': {
1927             name = optarg;
1928             APP_LOGD("bundle_test_tool %{public}s -m ext-name:%{public}s, %{public}s",
1929                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
1930             break;
1931         }
1932         case 't': {
1933             name = optarg;
1934             APP_LOGD("bundle_test_tool %{public}s -m mime-type:%{public}s, %{public}s",
1935                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
1936             break;
1937         }
1938         default: {
1939             std::string unknownOption = "";
1940             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1941             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1942             resultReceiver_.append(unknownOptionMsg);
1943             ret = false;
1944             break;
1945         }
1946     }
1947     return ret;
1948 }
1949 
RunAsSetExtNameOrMIMEToAppCommand()1950 ErrCode BundleTestTool::RunAsSetExtNameOrMIMEToAppCommand()
1951 {
1952     int result = OHOS::ERR_OK;
1953     int counter = 0;
1954     std::string commandName = "setExtNameOrMimeToApp";
1955     std::string name = "";
1956     std::string bundleName = "";
1957     std::string moduleName = "";
1958     std::string abilityName = "";
1959     std::string extName = "";
1960     std::string mimeType = "";
1961     APP_LOGD("RunAsSetExtNameOrMIMEToAppCommand is start");
1962     while (true) {
1963         counter++;
1964         int32_t option = getopt_long(
1965             argc_, argv_, SHORT_OPTIONS_MIME.c_str(), LONG_OPTIONS_MIME, nullptr);
1966         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1967         if (optind < 0 || optind > argc_) {
1968             return OHOS::ERR_INVALID_VALUE;
1969         }
1970         if (option == -1) {
1971             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1972                 APP_LOGD("bundle_test_tool RunAsSetExtNameOrMIMEToAppCommand with no option.");
1973                 resultReceiver_.append(HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE);
1974                 return OHOS::ERR_INVALID_VALUE;
1975             }
1976             break;
1977         }
1978         int temp = 0;
1979         result = !CheckExtOrMimeCorrectOption(option, commandName, temp, name)
1980                  ? OHOS::ERR_INVALID_VALUE : result;
1981         moduleName = option == 'm' ? name : moduleName;
1982         bundleName = option == 'n' ? name : bundleName;
1983         abilityName = option == 'a' ? name : abilityName;
1984         extName = option == 'e' ? name : extName;
1985         mimeType = option == 't' ? name : mimeType;
1986     }
1987 
1988     if (result != OHOS::ERR_OK) {
1989         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
1990     } else {
1991         result = bundleMgrProxy_->SetExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
1992         if (result == ERR_OK) {
1993             resultReceiver_.append("SetExtNameOrMIMEToApp succeeded,");
1994         } else {
1995             resultReceiver_.append("SetExtNameOrMIMEToApp failed, errCode is "+ std::to_string(result) + "\n");
1996         }
1997     }
1998     return result;
1999 }
2000 
RunAsDelExtNameOrMIMEToAppCommand()2001 ErrCode BundleTestTool::RunAsDelExtNameOrMIMEToAppCommand()
2002 {
2003     int result = OHOS::ERR_OK;
2004     int counter = 0;
2005     std::string commandName = "delExtNameOrMimeToApp";
2006     std::string name = "";
2007     std::string bundleName = "";
2008     std::string moduleName = "";
2009     std::string abilityName = "";
2010     std::string extName = "";
2011     std::string mimeType = "";
2012     APP_LOGD("RunAsDelExtNameOrMIMEToAppCommand is start");
2013     while (true) {
2014         counter++;
2015         int32_t option = getopt_long(
2016             argc_, argv_, SHORT_OPTIONS_MIME.c_str(), LONG_OPTIONS_MIME, nullptr);
2017         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2018         if (optind < 0 || optind > argc_) {
2019             return OHOS::ERR_INVALID_VALUE;
2020         }
2021         if (option == -1) {
2022             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2023                 APP_LOGD("bundle_test_tool RunAsDelExtNameOrMIMEToAppCommand with no option.");
2024                 resultReceiver_.append(HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE);
2025                 return OHOS::ERR_INVALID_VALUE;
2026             }
2027             break;
2028         }
2029         int temp = 0;
2030         result = !CheckExtOrMimeCorrectOption(option, commandName, temp, name)
2031                  ? OHOS::ERR_INVALID_VALUE : result;
2032         moduleName = option == 'm' ? name : moduleName;
2033         bundleName = option == 'n' ? name : bundleName;
2034         abilityName = option == 'a' ? name : abilityName;
2035         extName = option == 'e' ? name : extName;
2036         mimeType = option == 't' ? name : mimeType;
2037     }
2038 
2039     if (result != OHOS::ERR_OK) {
2040         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2041     } else {
2042         result = bundleMgrProxy_->DelExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
2043         if (result == ERR_OK) {
2044             resultReceiver_.append("DelExtNameOrMIMEToApp succeeded");
2045         } else {
2046             resultReceiver_.append("DelExtNameOrMIMEToApp failed, errCode is "+ std::to_string(result) + "\n");
2047         }
2048     }
2049     return result;
2050 }
2051 
CheckGetIconCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2052 bool BundleTestTool::CheckGetIconCorrectOption(
2053     int option, const std::string &commandName, int &temp, std::string &name)
2054 {
2055     bool ret = true;
2056     switch (option) {
2057         case 'h': {
2058             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2059             ret = false;
2060             break;
2061         }
2062         case 'n': {
2063             name = optarg;
2064             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
2065             break;
2066         }
2067         case 'm': {
2068             name = optarg;
2069             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
2070                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
2071             break;
2072         }
2073         case 'u': {
2074             StringToInt(optarg, commandName, temp, ret);
2075             break;
2076         }
2077         case 'i': {
2078             StringToInt(optarg, commandName, temp, ret);
2079             break;
2080         }
2081         case 'd': {
2082             StringToInt(optarg, commandName, temp, ret);
2083             break;
2084         }
2085         default: {
2086             std::string unknownOption = "";
2087             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2088             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2089             resultReceiver_.append(unknownOptionMsg);
2090             ret = false;
2091             break;
2092         }
2093     }
2094     return ret;
2095 }
2096 
RunAsGetIconCommand()2097 ErrCode BundleTestTool::RunAsGetIconCommand()
2098 {
2099     int result = OHOS::ERR_OK;
2100     int counter = 0;
2101     std::string commandName = "getIcon";
2102     std::string name = "";
2103     std::string bundleName = "";
2104     std::string moduleName = "";
2105     int userId = 100;
2106     int iconId = 0;
2107     int density = 0;
2108     APP_LOGD("RunAsGetIconCommand is start");
2109     while (true) {
2110         counter++;
2111         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
2112         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2113         if (optind < 0 || optind > argc_) {
2114             return OHOS::ERR_INVALID_VALUE;
2115         }
2116         if (option == -1) {
2117             // When scanning the first argument
2118             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2119                 // 'GetIconById' with no option: GetStringById
2120                 // 'GetIconById' with a wrong argument: GetStringById
2121                 APP_LOGD("bundle_test_tool getIcon with no option.");
2122                 resultReceiver_.append(HELP_MSG_NO_GETICON_OPTION);
2123                 return OHOS::ERR_INVALID_VALUE;
2124             }
2125             break;
2126         }
2127         int temp = 0;
2128         result = !CheckGetIconCorrectOption(option, commandName, temp, name)
2129             ? OHOS::ERR_INVALID_VALUE : result;
2130         moduleName = option == 'm' ? name : moduleName;
2131         bundleName = option == 'n' ? name : bundleName;
2132         userId = option == 'u' ? temp : userId;
2133         iconId = option == 'i' ? temp : iconId;
2134         density = option == 'd' ? temp : density;
2135     }
2136 
2137     if (result != OHOS::ERR_OK) {
2138         resultReceiver_.append(HELP_MSG_GET_ICON);
2139     } else {
2140         std::string results = "";
2141         results = bundleMgrProxy_->GetIconById(bundleName, moduleName, iconId, density, userId);
2142         if (results.empty()) {
2143             resultReceiver_.append(STRING_GET_ICON_NG);
2144             return result;
2145         }
2146         resultReceiver_.append(results);
2147     }
2148     return result;
2149 }
2150 
CheckAddInstallRuleCorrectOption(int option,const std::string & commandName,std::vector<std::string> & appIds,int & controlRuleType,int & userId,int & euid)2151 ErrCode BundleTestTool::CheckAddInstallRuleCorrectOption(int option, const std::string &commandName,
2152     std::vector<std::string> &appIds, int &controlRuleType, int &userId, int &euid)
2153 {
2154     bool ret = true;
2155     switch (option) {
2156         case 'h': {
2157             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2158             return OHOS::ERR_INVALID_VALUE;
2159         }
2160         case 'a': {
2161             std::string arrayAppId = optarg;
2162             std::stringstream array(arrayAppId);
2163             std::string object;
2164             while (getline(array, object, ',')) {
2165                 appIds.emplace_back(object);
2166             }
2167             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
2168             break;
2169         }
2170         case 'e': {
2171             StringToInt(optarg, commandName, euid, ret);
2172             break;
2173         }
2174         case 't': {
2175             StringToInt(optarg, commandName, controlRuleType, ret);
2176             break;
2177         }
2178         case 'u': {
2179             StringToInt(optarg, commandName, userId, ret);
2180             break;
2181         }
2182         default: {
2183             std::string unknownOption = "";
2184             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2185             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2186             resultReceiver_.append(unknownOptionMsg);
2187             return OHOS::ERR_INVALID_VALUE;
2188         }
2189     }
2190     return OHOS::ERR_OK;
2191 }
2192 
2193 // bundle_test_tool addAppInstallRule -a test1,test2 -t 1 -u 101 -e 3057
RunAsAddInstallRuleCommand()2194 ErrCode BundleTestTool::RunAsAddInstallRuleCommand()
2195 {
2196     ErrCode result = OHOS::ERR_OK;
2197     int counter = 0;
2198     std::string commandName = "addAppInstallRule";
2199     std::vector<std::string> appIds;
2200     int euid = 3057;
2201     int userId = 100;
2202     int ruleType = 0;
2203     APP_LOGD("RunAsAddInstallRuleCommand is start");
2204     while (true) {
2205         counter++;
2206         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2207         if (optind < 0 || optind > argc_) {
2208             return OHOS::ERR_INVALID_VALUE;
2209         }
2210         if (option == -1) {
2211             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2212                 resultReceiver_.append(HELP_MSG_NO_ADD_INSTALL_RULE_OPTION);
2213                 return OHOS::ERR_INVALID_VALUE;
2214             }
2215             break;
2216         }
2217         result = CheckAddInstallRuleCorrectOption(option, commandName, appIds, ruleType, userId, euid);
2218         if (result != OHOS::ERR_OK) {
2219             resultReceiver_.append(HELP_MSG_ADD_INSTALL_RULE);
2220             return OHOS::ERR_INVALID_VALUE;
2221         }
2222     }
2223     seteuid(euid);
2224     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2225     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2226     if (!appControlProxy) {
2227         APP_LOGE("fail to get app control proxy.");
2228         return OHOS::ERR_INVALID_VALUE;
2229     }
2230     std::string appIdParam = "";
2231     for (auto param : appIds) {
2232         appIdParam = appIdParam.append(param) + ";";
2233     }
2234     APP_LOGI("appIds: %{public}s, controlRuleType: %{public}d, userId: %{public}d",
2235         appIdParam.c_str(), ruleType, userId);
2236     int32_t res = appControlProxy->AddAppInstallControlRule(appIds, rule, userId);
2237     APP_LOGI("AddAppInstallControlRule return code: %{public}d", res);
2238     if (res != OHOS::ERR_OK) {
2239         resultReceiver_.append(STRING_ADD_RULE_NG);
2240         return res;
2241     }
2242     resultReceiver_.append(std::to_string(res) + "\n");
2243     return result;
2244 }
2245 
CheckGetInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)2246 ErrCode BundleTestTool::CheckGetInstallRuleCorrectOption(int option, const std::string &commandName,
2247     int &controlRuleType, int &userId, int &euid)
2248 {
2249     bool ret = true;
2250     switch (option) {
2251         case 'h': {
2252             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2253             return OHOS::ERR_INVALID_VALUE;
2254         }
2255         case 'e': {
2256             StringToInt(optarg, commandName, euid, ret);
2257             break;
2258         }
2259         case 't': {
2260             StringToInt(optarg, commandName, controlRuleType, ret);
2261             break;
2262         }
2263         case 'u': {
2264             StringToInt(optarg, commandName, userId, ret);
2265             break;
2266         }
2267         default: {
2268             std::string unknownOption = "";
2269             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2270             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2271             resultReceiver_.append(unknownOptionMsg);
2272             return OHOS::ERR_INVALID_VALUE;
2273         }
2274     }
2275     return OHOS::ERR_OK;
2276 }
2277 
2278 // bundle_test_tool getAppInstallRule -t 1 -u 101 -e 3057
RunAsGetInstallRuleCommand()2279 ErrCode BundleTestTool::RunAsGetInstallRuleCommand()
2280 {
2281     ErrCode result = OHOS::ERR_OK;
2282     int counter = 0;
2283     std::string commandName = "getAppInstallRule";
2284     int euid = 3057;
2285     int userId = 100;
2286     int ruleType = 0;
2287     APP_LOGD("RunAsGetInstallRuleCommand is start");
2288     while (true) {
2289         counter++;
2290         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2291         if (optind < 0 || optind > argc_) {
2292             return OHOS::ERR_INVALID_VALUE;
2293         }
2294         if (option == -1) {
2295             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2296                 resultReceiver_.append(HELP_MSG_NO_GET_INSTALL_RULE_OPTION);
2297                 return OHOS::ERR_INVALID_VALUE;
2298             }
2299             break;
2300         }
2301         result = CheckGetInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
2302         if (result != OHOS::ERR_OK) {
2303             resultReceiver_.append(HELP_MSG_GET_INSTALL_RULE);
2304             return OHOS::ERR_INVALID_VALUE;
2305         }
2306     }
2307     seteuid(euid);
2308     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2309     if (!appControlProxy) {
2310         APP_LOGE("fail to get app control proxy.");
2311         return OHOS::ERR_INVALID_VALUE;
2312     }
2313     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
2314     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2315     std::vector<std::string> appIds;
2316     int32_t res = appControlProxy->GetAppInstallControlRule(rule, userId, appIds);
2317     APP_LOGI("GetAppInstallControlRule return code: %{public}d", res);
2318     if (res != OHOS::ERR_OK) {
2319         resultReceiver_.append(STRING_GET_RULE_NG);
2320         return res;
2321     }
2322     std::string appIdParam = "";
2323     for (auto param : appIds) {
2324         appIdParam = appIdParam.append(param) + "; ";
2325     }
2326     resultReceiver_.append("appId : " + appIdParam + "\n");
2327     return result;
2328 }
2329 
CheckDeleteInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,std::vector<std::string> & appIds,int & userId,int & euid)2330 ErrCode BundleTestTool::CheckDeleteInstallRuleCorrectOption(int option, const std::string &commandName,
2331     int &controlRuleType, std::vector<std::string> &appIds, int &userId, int &euid)
2332 {
2333     bool ret = true;
2334     switch (option) {
2335         case 'h': {
2336             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2337             return OHOS::ERR_INVALID_VALUE;
2338         }
2339         case 'a': {
2340             std::string arrayAppId = optarg;
2341             std::stringstream array(arrayAppId);
2342             std::string object;
2343             while (getline(array, object, ',')) {
2344                 appIds.emplace_back(object);
2345             }
2346             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
2347             break;
2348         }
2349         case 'e': {
2350             StringToInt(optarg, commandName, euid, ret);
2351             break;
2352         }
2353         case 't': {
2354             StringToInt(optarg, commandName, controlRuleType, ret);
2355             break;
2356         }
2357         case 'u': {
2358             StringToInt(optarg, commandName, userId, ret);
2359             break;
2360         }
2361         default: {
2362             std::string unknownOption = "";
2363             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2364             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2365             resultReceiver_.append(unknownOptionMsg);
2366             return OHOS::ERR_INVALID_VALUE;
2367         }
2368     }
2369     return OHOS::ERR_OK;
2370 }
2371 
2372 // bundle_test_tool deleteAppInstallRule -a test1 -t 1 -u 101 -e 3057
RunAsDeleteInstallRuleCommand()2373 ErrCode BundleTestTool::RunAsDeleteInstallRuleCommand()
2374 {
2375     ErrCode result = OHOS::ERR_OK;
2376     int counter = 0;
2377     int euid = 3057;
2378     std::string commandName = "deleteAppInstallRule";
2379     std::vector<std::string> appIds;
2380     int ruleType = 0;
2381     int userId = 100;
2382     APP_LOGD("RunAsDeleteInstallRuleCommand is start");
2383     while (true) {
2384         counter++;
2385         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2386         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2387         if (optind < 0 || optind > argc_) {
2388             return OHOS::ERR_INVALID_VALUE;
2389         }
2390         if (option == -1) {
2391             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2392                 resultReceiver_.append(HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION);
2393                 return OHOS::ERR_INVALID_VALUE;
2394             }
2395             break;
2396         }
2397         result = CheckDeleteInstallRuleCorrectOption(option, commandName, ruleType, appIds, userId, euid);
2398         if (result != OHOS::ERR_OK) {
2399             resultReceiver_.append(HELP_MSG_DELETE_INSTALL_RULE);
2400             return OHOS::ERR_INVALID_VALUE;
2401         }
2402     }
2403     seteuid(euid);
2404     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2405     if (!appControlProxy) {
2406         APP_LOGE("fail to get app control proxy.");
2407         return OHOS::ERR_INVALID_VALUE;
2408     }
2409     std::string appIdParam = "";
2410     for (auto param : appIds) {
2411         appIdParam = appIdParam.append(param) + ";";
2412     }
2413     APP_LOGI("appIds: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2414     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2415     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, appIds, userId);
2416     APP_LOGI("DeleteAppInstallControlRule return code: %{public}d", res);
2417     if (res != OHOS::ERR_OK) {
2418         resultReceiver_.append(STRING_DELETE_RULE_NG);
2419         return res;
2420     }
2421     resultReceiver_.append(std::to_string(res) + "\n");
2422     return result;
2423 }
2424 
CheckCleanInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)2425 ErrCode BundleTestTool::CheckCleanInstallRuleCorrectOption(
2426     int option, const std::string &commandName, int &controlRuleType, int &userId, int &euid)
2427 {
2428     bool ret = true;
2429     switch (option) {
2430         case 'h': {
2431             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2432             return OHOS::ERR_INVALID_VALUE;
2433         }
2434         case 'e': {
2435             StringToInt(optarg, commandName, euid, ret);
2436             break;
2437         }
2438         case 't': {
2439             StringToInt(optarg, commandName, controlRuleType, ret);
2440             break;
2441         }
2442         case 'u': {
2443             StringToInt(optarg, commandName, userId, ret);
2444             break;
2445         }
2446         default: {
2447             std::string unknownOption = "";
2448             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2449             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2450             resultReceiver_.append(unknownOptionMsg);
2451             return OHOS::ERR_INVALID_VALUE;
2452         }
2453     }
2454     return OHOS::ERR_OK;
2455 }
2456 
2457 // bundle_test_tool cleanAppInstallRule -t 1 -u 101 -e 3057
RunAsCleanInstallRuleCommand()2458 ErrCode BundleTestTool::RunAsCleanInstallRuleCommand()
2459 {
2460     ErrCode result = OHOS::ERR_OK;
2461     int counter = 0;
2462     int euid = 3057;
2463     std::string commandName = "cleanAppInstallRule";
2464     int userId = 100;
2465     int ruleType = 0;
2466     APP_LOGD("RunAsCleanInstallRuleCommand is start");
2467     while (true) {
2468         counter++;
2469         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2470         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2471         if (optind < 0 || optind > argc_) {
2472             return OHOS::ERR_INVALID_VALUE;
2473         }
2474         if (option == -1) {
2475             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2476                 APP_LOGD("bundle_test_tool getRule with no option.");
2477                 resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
2478                 return OHOS::ERR_INVALID_VALUE;
2479             }
2480             break;
2481         }
2482         result = CheckCleanInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
2483         if (result != OHOS::ERR_OK) {
2484             resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
2485             return OHOS::ERR_INVALID_VALUE;
2486         }
2487     }
2488     seteuid(euid);
2489     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2490     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2491     if (!appControlProxy) {
2492         APP_LOGE("fail to get app control proxy.");
2493         return OHOS::ERR_INVALID_VALUE;
2494     }
2495     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
2496     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, userId);
2497     APP_LOGI("DeleteAppInstallControlRule clean return code: %{public}d", res);
2498     if (res != OHOS::ERR_OK) {
2499         resultReceiver_.append(STRING_DELETE_RULE_NG);
2500         return res;
2501     }
2502     resultReceiver_.append(std::to_string(res) + "\n");
2503     return result;
2504 }
2505 
CheckAppRunningRuleCorrectOption(int option,const std::string & commandName,std::vector<AppRunningControlRule> & controlRule,int & userId,int & euid)2506 ErrCode BundleTestTool::CheckAppRunningRuleCorrectOption(int option, const std::string &commandName,
2507     std::vector<AppRunningControlRule> &controlRule, int &userId, int &euid)
2508 {
2509     bool ret = true;
2510     switch (option) {
2511         case 'h': {
2512             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2513             return OHOS::ERR_INVALID_VALUE;
2514         }
2515         case 'c': {
2516             std::string arrayJsonRule = optarg;
2517             std::stringstream array(arrayJsonRule);
2518             std::string object;
2519             while (getline(array, object, ';')) {
2520                 size_t pos1 = object.find("appId");
2521                 size_t pos2 = object.find("controlMessage");
2522                 size_t pos3 = object.find(":", pos2);
2523                 if ((pos1 == std::string::npos) || (pos2 == std::string::npos)) {
2524                     return OHOS::ERR_INVALID_VALUE;
2525                 }
2526                 std::string appId = object.substr(pos1+6, pos2-pos1-7);
2527                 std::string controlMessage = object.substr(pos3+1);
2528                 AppRunningControlRule rule;
2529                 rule.appId = appId;
2530                 rule.controlMessage = controlMessage;
2531                 controlRule.emplace_back(rule);
2532             }
2533             break;
2534         }
2535         case 'e': {
2536             StringToInt(optarg, commandName, euid, ret);
2537             break;
2538         }
2539         case 'u': {
2540             StringToInt(optarg, commandName, userId, ret);
2541             break;
2542         }
2543         default: {
2544             std::string unknownOption = "";
2545             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2546             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2547             resultReceiver_.append(unknownOptionMsg);
2548             return OHOS::ERR_INVALID_VALUE;
2549         }
2550     }
2551     return OHOS::ERR_OK;
2552 }
2553 
2554 // bundle_test_tool addAppRunningRule -c appId:id1,controlMessage:msg1;appId:id2,controlMessage:msg2
2555 // -u 101 -e 3057
RunAsAddAppRunningRuleCommand()2556 ErrCode BundleTestTool::RunAsAddAppRunningRuleCommand()
2557 {
2558     ErrCode result = OHOS::ERR_OK;
2559     int counter = 0;
2560     int euid = 3057;
2561     std::string commandName = "addAppRunningRule";
2562     int userId = 100;
2563     std::vector<AppRunningControlRule> controlRule;
2564     APP_LOGD("RunAsAddAppRunningRuleCommand is start");
2565     while (true) {
2566         counter++;
2567         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2568         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2569         if (optind < 0 || optind > argc_) {
2570             return OHOS::ERR_INVALID_VALUE;
2571         }
2572         if (option == -1) {
2573             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2574                 APP_LOGD("bundle_test_tool getRule with no option.");
2575                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
2576                 return OHOS::ERR_INVALID_VALUE;
2577             }
2578             break;
2579         }
2580         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
2581         if (result != OHOS::ERR_OK) {
2582             resultReceiver_.append(HELP_MSG_ADD_APP_RUNNING_RULE);
2583             return OHOS::ERR_INVALID_VALUE;
2584         }
2585     }
2586     seteuid(euid);
2587     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2588     if (!appControlProxy) {
2589         APP_LOGE("fail to get app control proxy.");
2590         return OHOS::ERR_INVALID_VALUE;
2591     }
2592     std::string appIdParam = "";
2593     for (auto param : controlRule) {
2594         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
2595     }
2596     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2597     int32_t res = appControlProxy->AddAppRunningControlRule(controlRule, userId);
2598     if (res != OHOS::ERR_OK) {
2599         resultReceiver_.append(STRING_ADD_RULE_NG);
2600         return res;
2601     }
2602     resultReceiver_.append(std::to_string(res) + "\n");
2603     return result;
2604 }
2605 
2606 // bundle_test_tool deleteAppRunningRule -c appId:101,controlMessage:msg1 -u 101 -e 3057
RunAsDeleteAppRunningRuleCommand()2607 ErrCode BundleTestTool::RunAsDeleteAppRunningRuleCommand()
2608 {
2609     ErrCode result = OHOS::ERR_OK;
2610     int counter = 0;
2611     int euid = 3057;
2612     std::string commandName = "addAppRunningRule";
2613     int userId = 100;
2614     std::vector<AppRunningControlRule> controlRule;
2615     APP_LOGD("RunAsDeleteAppRunningRuleCommand is start");
2616     while (true) {
2617         counter++;
2618         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2619         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2620         if (optind < 0 || optind > argc_) {
2621             return OHOS::ERR_INVALID_VALUE;
2622         }
2623         if (option == -1) {
2624             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2625                 APP_LOGD("bundle_test_tool getRule with no option.");
2626                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
2627                 return OHOS::ERR_INVALID_VALUE;
2628             }
2629             break;
2630         }
2631         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
2632         if (result != OHOS::ERR_OK) {
2633             resultReceiver_.append(HELP_MSG_DELETE_APP_RUNNING_RULE);
2634             return OHOS::ERR_INVALID_VALUE;
2635         }
2636     }
2637     seteuid(euid);
2638     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2639     if (!appControlProxy) {
2640         APP_LOGE("fail to get app control proxy.");
2641         return OHOS::ERR_INVALID_VALUE;
2642     }
2643     std::string appIdParam = "";
2644     for (auto param : controlRule) {
2645         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
2646     }
2647     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2648     int32_t res = appControlProxy->DeleteAppRunningControlRule(controlRule, userId);
2649     if (res != OHOS::ERR_OK) {
2650         resultReceiver_.append(STRING_DELETE_RULE_NG);
2651         return res;
2652     }
2653     resultReceiver_.append(std::to_string(res) + "\n");
2654     return result;
2655 }
2656 
CheckCleanAppRunningRuleCorrectOption(int option,const std::string & commandName,int & userId,int & euid)2657 ErrCode BundleTestTool::CheckCleanAppRunningRuleCorrectOption(
2658     int option, const std::string &commandName, int &userId, int &euid)
2659 {
2660     bool ret = true;
2661     switch (option) {
2662         case 'h': {
2663             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2664             return OHOS::ERR_INVALID_VALUE;
2665         }
2666         case 'e': {
2667             StringToInt(optarg, commandName, euid, ret);
2668             break;
2669         }
2670         case 'u': {
2671             StringToInt(optarg, commandName, userId, ret);
2672             break;
2673         }
2674         default: {
2675             std::string unknownOption = "";
2676             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2677             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2678             resultReceiver_.append(unknownOptionMsg);
2679             return OHOS::ERR_INVALID_VALUE;
2680         }
2681     }
2682     return OHOS::ERR_OK;
2683 }
2684 
2685 // bundle_test_tool cleanAppRunningRule -u 101 -e 3057
RunAsCleanAppRunningRuleCommand()2686 ErrCode BundleTestTool::RunAsCleanAppRunningRuleCommand()
2687 {
2688     ErrCode result = OHOS::ERR_OK;
2689     int counter = 0;
2690     int euid = 3057;
2691     std::string commandName = "addAppRunningRule";
2692     int userId = 100;
2693     APP_LOGD("RunAsCleanAppRunningRuleCommand is start");
2694     while (true) {
2695         counter++;
2696         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2697         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2698         if (optind < 0 || optind > argc_) {
2699             return OHOS::ERR_INVALID_VALUE;
2700         }
2701         if (option == -1) {
2702             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2703                 APP_LOGD("bundle_test_tool getRule with no option.");
2704                 resultReceiver_.append(HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION);
2705                 return OHOS::ERR_INVALID_VALUE;
2706             }
2707             break;
2708         }
2709         result = CheckCleanAppRunningRuleCorrectOption(option, commandName, userId, euid);
2710         if (result != OHOS::ERR_OK) {
2711             resultReceiver_.append(HELP_MSG_CLEAN_APP_RUNNING_RULE);
2712             return OHOS::ERR_INVALID_VALUE;
2713         }
2714     }
2715     seteuid(euid);
2716     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2717     if (!appControlProxy) {
2718         APP_LOGE("fail to get app control proxy.");
2719         return OHOS::ERR_INVALID_VALUE;
2720     }
2721     APP_LOGI("userId: %{public}d", userId);
2722     int32_t res = appControlProxy->DeleteAppRunningControlRule(userId);
2723     if (res != OHOS::ERR_OK) {
2724         resultReceiver_.append(STRING_DELETE_RULE_NG);
2725         return res;
2726     }
2727     resultReceiver_.append(std::to_string(res) + "\n");
2728     return result;
2729 }
2730 
CheckGetAppRunningRuleCorrectOption(int option,const std::string & commandName,int32_t & userId,int & euid)2731 ErrCode BundleTestTool::CheckGetAppRunningRuleCorrectOption(int option, const std::string &commandName,
2732     int32_t &userId, int &euid)
2733 {
2734     bool ret = true;
2735     switch (option) {
2736         case 'h': {
2737             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2738             return OHOS::ERR_INVALID_VALUE;
2739         }
2740         case 'e': {
2741             StringToInt(optarg, commandName, euid, ret);
2742             break;
2743         }
2744         case 'u': {
2745             StringToInt(optarg, commandName, userId, ret);
2746             break;
2747         }
2748         default: {
2749             std::string unknownOption = "";
2750             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2751             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2752             resultReceiver_.append(unknownOptionMsg);
2753             return OHOS::ERR_INVALID_VALUE;
2754         }
2755     }
2756     return OHOS::ERR_OK ;
2757 }
2758 
2759 // bundle_test_tool getAppRunningControlRule -u 101 -e 3057
RunAsGetAppRunningControlRuleCommand()2760 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleCommand()
2761 {
2762     ErrCode result = OHOS::ERR_OK;
2763     int counter = 0;
2764     int euid = 3057;
2765     std::string commandName = "addAppRunningRule";
2766     int userId = 100;
2767     APP_LOGD("RunAsGetAppRunningControlRuleCommand is start");
2768     while (true) {
2769         counter++;
2770         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2771         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2772         if (optind < 0 || optind > argc_) {
2773             return OHOS::ERR_INVALID_VALUE;
2774         }
2775         if (option == -1) {
2776             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2777                 APP_LOGD("bundle_test_tool getRule with no option.");
2778                 resultReceiver_.append(HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION);
2779                 return OHOS::ERR_INVALID_VALUE;
2780             }
2781             break;
2782         }
2783         result = CheckGetAppRunningRuleCorrectOption(option, commandName, userId, euid);
2784         if (result != OHOS::ERR_OK) {
2785             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RULE);
2786             return OHOS::ERR_INVALID_VALUE;
2787         }
2788     }
2789     seteuid(euid);
2790     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2791     if (!appControlProxy) {
2792         APP_LOGE("fail to get app control proxy.");
2793         return OHOS::ERR_INVALID_VALUE;
2794     }
2795     APP_LOGI("userId: %{public}d", userId);
2796     std::vector<std::string> appIds;
2797     int32_t res = appControlProxy->GetAppRunningControlRule(userId, appIds);
2798     if (res != OHOS::ERR_OK) {
2799         resultReceiver_.append(STRING_GET_RULE_NG);
2800         return res;
2801     }
2802     std::string appIdParam = "";
2803     for (auto param : appIds) {
2804         appIdParam = appIdParam.append(param) + "; ";
2805     }
2806     resultReceiver_.append("appId : " + appIdParam + "\n");
2807     return result;
2808 }
2809 
CheckGetAppRunningRuleResultCorrectOption(int option,const std::string & commandName,std::string & bundleName,int32_t & userId,int & euid)2810 ErrCode BundleTestTool::CheckGetAppRunningRuleResultCorrectOption(int option, const std::string &commandName,
2811     std::string &bundleName, int32_t &userId, int &euid)
2812 {
2813     bool ret = true;
2814     switch (option) {
2815         case 'h': {
2816             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2817             return OHOS::ERR_INVALID_VALUE;
2818         }
2819         case 'e': {
2820             StringToInt(optarg, commandName, euid, ret);
2821             break;
2822         }
2823         case 'n': {
2824             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
2825             bundleName = optarg;
2826             break;
2827         }
2828         case 'u': {
2829             StringToInt(optarg, commandName, userId, ret);
2830             break;
2831         }
2832         default: {
2833             std::string unknownOption = "";
2834             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2835             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2836             resultReceiver_.append(unknownOptionMsg);
2837             return OHOS::ERR_INVALID_VALUE;
2838         }
2839     }
2840     return OHOS::ERR_OK;
2841 }
2842 
2843 // bundle_test_tool getAppRunningControlRuleResult -n com.ohos.example -e 3057
RunAsGetAppRunningControlRuleResultCommand()2844 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleResultCommand()
2845 {
2846     ErrCode result = OHOS::ERR_OK;
2847     int counter = 0;
2848     int euid = 3057;
2849     std::string commandName = "addAppRunningRule";
2850     int userId = 100;
2851     std::string bundleName;
2852     APP_LOGD("RunAsGetAppRunningControlRuleResultCommand is start");
2853     while (true) {
2854         counter++;
2855         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2856         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2857         if (optind < 0 || optind > argc_) {
2858             return OHOS::ERR_INVALID_VALUE;
2859         }
2860         if (option == -1) {
2861             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2862                 APP_LOGD("bundle_test_tool getRule with no option.");
2863                 resultReceiver_.append(HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION);
2864                 return OHOS::ERR_INVALID_VALUE;
2865             }
2866             break;
2867         }
2868         result = CheckGetAppRunningRuleResultCorrectOption(option, commandName, bundleName, userId, euid);
2869         if (result != OHOS::ERR_OK) {
2870             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RESULT_RULE);
2871             return OHOS::ERR_INVALID_VALUE;
2872         }
2873     }
2874     seteuid(euid);
2875     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2876     if (!appControlProxy) {
2877         APP_LOGE("fail to get app control proxy.");
2878         return OHOS::ERR_INVALID_VALUE;
2879     }
2880     AppRunningControlRuleResult ruleResult;
2881     APP_LOGI("bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
2882     int32_t res = appControlProxy->GetAppRunningControlRule(bundleName, userId, ruleResult);
2883     if (res != OHOS::ERR_OK) {
2884         APP_LOGI("GetAppRunningControlRule result: %{public}d", res);
2885         resultReceiver_.append("message:" + ruleResult.controlMessage + " bundle:notFind" + "\n");
2886         return res;
2887     }
2888     resultReceiver_.append("message:" + ruleResult.controlMessage + "\n");
2889     if (ruleResult.controlWant != nullptr) {
2890         resultReceiver_.append("controlWant:" + ruleResult.controlWant->ToString() + "\n");
2891     } else {
2892         resultReceiver_.append("controlWant: nullptr \n");
2893     }
2894     return result;
2895 }
2896 
CheckCleanBundleCacheFilesAutomaticOption(int option,const std::string & commandName,uint64_t & cacheSize)2897 ErrCode BundleTestTool::CheckCleanBundleCacheFilesAutomaticOption(
2898     int option, const std::string &commandName, uint64_t &cacheSize)
2899 {
2900     bool ret = true;
2901     switch (option) {
2902         case 'h': {
2903             APP_LOGI("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2904             return OHOS::ERR_INVALID_VALUE;
2905         }
2906         case 's': {
2907             APP_LOGI("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2908             StringToUnsignedLongLong(optarg, commandName, cacheSize, ret);
2909             break;
2910         }
2911         default: {
2912             std::string unknownOption = "";
2913             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2914             APP_LOGE("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2915             resultReceiver_.append(unknownOptionMsg);
2916             return OHOS::ERR_INVALID_VALUE;
2917         }
2918     }
2919     return OHOS::ERR_OK;
2920 }
2921 
RunAsCleanBundleCacheFilesAutomaticCommand()2922 ErrCode BundleTestTool::RunAsCleanBundleCacheFilesAutomaticCommand()
2923 {
2924     ErrCode result = OHOS::ERR_OK;
2925     int counter = 0;
2926     std::string commandName = "cleanBundleCacheFilesAutomatic";
2927     uint64_t cacheSize;
2928     APP_LOGI("RunAsCleanBundleCacheFilesAutomaticCommand is start");
2929     while (true) {
2930         counter++;
2931         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_AUTO_CLEAN_CACHE.c_str(),
2932             LONG_OPTIONS_AUTO_CLEAN_CACHE, nullptr);
2933         APP_LOGI("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2934         if (optind < 0 || optind > argc_) {
2935             return OHOS::ERR_INVALID_VALUE;
2936         }
2937         if (option == -1) {
2938             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2939                 APP_LOGE("bundle_test_tool getRule with no option.");
2940                 resultReceiver_.append(HELP_MSG_NO_AUTO_CLEAN_CACHE_OPTION);
2941                 return OHOS::ERR_INVALID_VALUE;
2942             }
2943             break;
2944         }
2945         result = CheckCleanBundleCacheFilesAutomaticOption(option, commandName, cacheSize);
2946         if (result != OHOS::ERR_OK) {
2947             resultReceiver_.append(HELP_MSG_AUTO_CLEAN_CACHE_RULE);
2948             return OHOS::ERR_INVALID_VALUE;
2949         }
2950     }
2951 
2952     ErrCode res = bundleMgrProxy_->CleanBundleCacheFilesAutomatic(cacheSize);
2953     if (res == ERR_OK) {
2954         resultReceiver_.append("clean fixed size cache successfully\n");
2955     } else {
2956         resultReceiver_.append("clean fixed size cache failed, errCode is "+ std::to_string(res) + "\n");
2957         APP_LOGE("CleanBundleCacheFilesAutomatic failed, result: %{public}d", res);
2958         return res;
2959     }
2960 
2961     return res;
2962 }
2963 
RunAsGetContinueBundleName()2964 ErrCode BundleTestTool::RunAsGetContinueBundleName()
2965 {
2966     APP_LOGD("RunAsGetContinueBundleName start");
2967     std::string bundleName;
2968     int32_t userId = Constants::UNSPECIFIED_USERID;
2969     int32_t appIndex;
2970     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
2971     if (result != OHOS::ERR_OK) {
2972         resultReceiver_.append("RunAsGetContinueBundleName erro!!");
2973     } else {
2974         if (userId == Constants::UNSPECIFIED_USERID) {
2975             int32_t mockUid = 20010099;
2976             // Mock the current tool uid, the current default user must be executed under 100.
2977             int setResult = setuid(mockUid);
2978             APP_LOGD("Set uid result: %{public}d", setResult);
2979         }
2980 
2981         std::string msg;
2982         result = GetContinueBundleName(bundleName, userId, msg);
2983         APP_LOGD("Get continue bundle result %{public}d", result);
2984         if (result == OHOS::ERR_OK) {
2985             resultReceiver_.append(msg);
2986             return ERR_OK;
2987         } else {
2988             APP_LOGE("Get continue bundle name error: %{public}d", result);
2989             std::string err("Get continue bundle name error!");
2990             resultReceiver_.append(err);
2991         }
2992     }
2993     return OHOS::ERR_INVALID_VALUE;
2994 }
2995 
GetContinueBundleName(const std::string & bundleName,int32_t userId,std::string & msg)2996 ErrCode BundleTestTool::GetContinueBundleName(const std::string &bundleName, int32_t userId, std::string& msg)
2997 {
2998     if (bundleMgrProxy_ == nullptr) {
2999         APP_LOGE("Bundle mgr proxy is nullptr");
3000         return OHOS::ERR_INVALID_VALUE;
3001     }
3002     std::vector<std::string> continueBundleName;
3003     auto ret = bundleMgrProxy_->GetContinueBundleNames(bundleName, continueBundleName, userId);
3004     APP_LOGD("Get continue bundle names result: %{public}d", ret);
3005     if (ret == OHOS::ERR_OK) {
3006         msg = "continueBundleNameList:\n{\n";
3007         for (const auto &name : continueBundleName) {
3008             msg +="     ";
3009             msg += name;
3010             msg += "\n";
3011         }
3012         msg += "}\n";
3013         return ERR_OK;
3014     }
3015     return ret;
3016 }
3017 
RunAsDeployQuickFix()3018 ErrCode BundleTestTool::RunAsDeployQuickFix()
3019 {
3020     int32_t result = OHOS::ERR_OK;
3021     int32_t counter = 0;
3022     int32_t index = 0;
3023     std::vector<std::string> quickFixPaths;
3024     int32_t isDebug = 0;
3025     while (true) {
3026         counter++;
3027         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3028         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3029         if (optind < 0 || optind > argc_) {
3030             return OHOS::ERR_INVALID_VALUE;
3031         }
3032 
3033         if (option == -1 || option == '?') {
3034             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3035                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3036                 result = OHOS::ERR_INVALID_VALUE;
3037                 break;
3038             }
3039             if ((optopt == 'p') || (optopt == 'd')) {
3040                 // 'bm deployQuickFix --patch-path' with no argument
3041                 // 'bm deployQuickFix -d' with no argument
3042                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3043                 result = OHOS::ERR_INVALID_VALUE;
3044                 break;
3045             }
3046             break;
3047         }
3048 
3049         if (option == 'p') {
3050             APP_LOGD("'bm deployQuickFix -p %{public}s'", argv_[optind - 1]);
3051             quickFixPaths.emplace_back(optarg);
3052             index = optind;
3053             continue;
3054         }
3055         if ((option == 'd') && OHOS::StrToInt(optarg, isDebug)) {
3056             APP_LOGD("'bm deployQuickFix -d %{public}s'", argv_[optind - 1]);
3057             continue;
3058         }
3059 
3060         result = OHOS::ERR_INVALID_VALUE;
3061         break;
3062     }
3063 
3064     if (result != OHOS::ERR_OK || GetQuickFixPath(index, quickFixPaths) != OHOS::ERR_OK) {
3065         resultReceiver_.append(HELP_MSG_DEPLOY_QUICK_FIX);
3066         return result;
3067     }
3068 
3069     std::shared_ptr<QuickFixResult> deployRes = nullptr;
3070     result = DeployQuickFix(quickFixPaths, deployRes, isDebug != 0);
3071     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DEPLOY_QUICK_FIX_OK : STRING_DEPLOY_QUICK_FIX_NG;
3072     resultReceiver_ += GetResMsg(result, deployRes);
3073 
3074     return result;
3075 }
3076 
GetQuickFixPath(int32_t index,std::vector<std::string> & quickFixPaths) const3077 ErrCode BundleTestTool::GetQuickFixPath(int32_t index, std::vector<std::string>& quickFixPaths) const
3078 {
3079     APP_LOGI("GetQuickFixPath start");
3080     for (; index < argc_ && index >= INDEX_OFFSET; ++index) {
3081         if (argList_[index - INDEX_OFFSET] == "-p" || argList_[index - INDEX_OFFSET] == "--patch-path") {
3082             break;
3083         }
3084 
3085         std::string innerPath = argList_[index - INDEX_OFFSET];
3086         if (innerPath.empty() || innerPath == "-p" || innerPath == "--patch-path") {
3087             quickFixPaths.clear();
3088             return OHOS::ERR_INVALID_VALUE;
3089         }
3090         APP_LOGD("GetQuickFixPath is %{public}s'", innerPath.c_str());
3091         quickFixPaths.emplace_back(innerPath);
3092     }
3093     return OHOS::ERR_OK;
3094 }
3095 
RunAsSwitchQuickFix()3096 ErrCode BundleTestTool::RunAsSwitchQuickFix()
3097 {
3098     int32_t result = OHOS::ERR_OK;
3099     int32_t counter = 0;
3100     int32_t enable = -1;
3101     std::string bundleName;
3102     while (true) {
3103         counter++;
3104         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3105         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3106         if (optind < 0 || optind > argc_) {
3107             return OHOS::ERR_INVALID_VALUE;
3108         }
3109 
3110         if (option == -1 || option == '?') {
3111             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3112                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3113                 result = OHOS::ERR_INVALID_VALUE;
3114                 break;
3115             }
3116             if (optopt == 'n' || optopt == 'e') {
3117                 // 'bm switchQuickFix -n -e' with no argument
3118                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3119                 result = OHOS::ERR_INVALID_VALUE;
3120                 break;
3121             }
3122             break;
3123         }
3124 
3125         if (option == 'n') {
3126             APP_LOGD("'bm switchQuickFix -n %{public}s'", argv_[optind - 1]);
3127             bundleName = optarg;
3128             continue;
3129         }
3130         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
3131             APP_LOGD("'bm switchQuickFix -e %{public}s'", argv_[optind - 1]);
3132             continue;
3133         }
3134         result = OHOS::ERR_INVALID_VALUE;
3135         break;
3136     }
3137 
3138     if ((result != OHOS::ERR_OK) || (enable < 0) || (enable > 1)) {
3139         resultReceiver_.append(HELP_MSG_SWITCH_QUICK_FIX);
3140         return result;
3141     }
3142     std::shared_ptr<QuickFixResult> switchRes = nullptr;
3143     result = SwitchQuickFix(bundleName, enable, switchRes);
3144     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_SWITCH_QUICK_FIX_OK : STRING_SWITCH_QUICK_FIX_NG;
3145     resultReceiver_ += GetResMsg(result, switchRes);
3146 
3147     return result;
3148 }
3149 
RunAsDeleteQuickFix()3150 ErrCode BundleTestTool::RunAsDeleteQuickFix()
3151 {
3152     int32_t result = OHOS::ERR_OK;
3153     int32_t counter = 0;
3154     std::string bundleName;
3155     while (true) {
3156         counter++;
3157         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3158         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3159         if (optind < 0 || optind > argc_) {
3160             return OHOS::ERR_INVALID_VALUE;
3161         }
3162 
3163         if (option == -1 || option == '?') {
3164             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3165                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3166                 result = OHOS::ERR_INVALID_VALUE;
3167                 break;
3168             }
3169             if (optopt == 'n') {
3170                 // 'bm deleteQuickFix -n' with no argument
3171                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3172                 result = OHOS::ERR_INVALID_VALUE;
3173                 break;
3174             }
3175             break;
3176         }
3177 
3178         if (option == 'n') {
3179             APP_LOGD("'bm deleteQuickFix -n %{public}s'", argv_[optind - 1]);
3180             bundleName = optarg;
3181             continue;
3182         }
3183         result = OHOS::ERR_INVALID_VALUE;
3184         break;
3185     }
3186 
3187     if (result != OHOS::ERR_OK) {
3188         resultReceiver_.append(HELP_MSG_DELETE_QUICK_FIX);
3189         return result;
3190     }
3191     std::shared_ptr<QuickFixResult> deleteRes = nullptr;
3192     result = DeleteQuickFix(bundleName, deleteRes);
3193     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DELETE_QUICK_FIX_OK : STRING_DELETE_QUICK_FIX_NG;
3194     resultReceiver_ += GetResMsg(result, deleteRes);
3195 
3196     return result;
3197 }
3198 
DeployQuickFix(const std::vector<std::string> & quickFixPaths,std::shared_ptr<QuickFixResult> & quickFixRes,bool isDebug)3199 ErrCode BundleTestTool::DeployQuickFix(const std::vector<std::string> &quickFixPaths,
3200     std::shared_ptr<QuickFixResult> &quickFixRes, bool isDebug)
3201 {
3202 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3203     std::set<std::string> realPathSet;
3204     for (const auto &quickFixPath : quickFixPaths) {
3205         std::string realPath;
3206         if (!PathToRealPath(quickFixPath, realPath)) {
3207             APP_LOGW("quickFixPath %{public}s is invalid", quickFixPath.c_str());
3208             continue;
3209         }
3210         APP_LOGD("realPath is %{public}s", realPath.c_str());
3211         realPathSet.insert(realPath);
3212     }
3213     std::vector<std::string> pathVec(realPathSet.begin(), realPathSet.end());
3214 
3215     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3216     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3217         APP_LOGE("callback or bundleMgrProxy is null");
3218         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3219     }
3220     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3221     if (recipient == nullptr) {
3222         APP_LOGE("recipient is null");
3223         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3224     }
3225     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3226     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3227     if (quickFixProxy == nullptr) {
3228         APP_LOGE("quickFixProxy is null");
3229         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3230     }
3231     std::vector<std::string> destFiles;
3232     auto res = quickFixProxy->CopyFiles(pathVec, destFiles);
3233     if (res != ERR_OK) {
3234         APP_LOGE("Copy files failed with %{public}d.", res);
3235         return res;
3236     }
3237     res = quickFixProxy->DeployQuickFix(destFiles, callback, isDebug);
3238     if (res != ERR_OK) {
3239         APP_LOGE("DeployQuickFix failed");
3240         return res;
3241     }
3242 
3243     return callback->GetResultCode(quickFixRes);
3244 #else
3245     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3246 #endif
3247 }
3248 
SwitchQuickFix(const std::string & bundleName,int32_t enable,std::shared_ptr<QuickFixResult> & quickFixRes)3249 ErrCode BundleTestTool::SwitchQuickFix(const std::string &bundleName, int32_t enable,
3250     std::shared_ptr<QuickFixResult> &quickFixRes)
3251 {
3252     APP_LOGD("SwitchQuickFix bundleName: %{public}s, enable: %{public}d", bundleName.c_str(), enable);
3253 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3254     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3255     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3256         APP_LOGE("callback or bundleMgrProxy is null");
3257         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3258     }
3259     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3260     if (recipient == nullptr) {
3261         APP_LOGE("recipient is null");
3262         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3263     }
3264     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3265     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3266     if (quickFixProxy == nullptr) {
3267         APP_LOGE("quickFixProxy is null");
3268         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3269     }
3270     bool enableFlag = (enable == 0) ? false : true;
3271     auto res = quickFixProxy->SwitchQuickFix(bundleName, enableFlag, callback);
3272     if (res != ERR_OK) {
3273         APP_LOGE("SwitchQuickFix failed");
3274         return res;
3275     }
3276     return callback->GetResultCode(quickFixRes);
3277 #else
3278     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3279 #endif
3280 }
3281 
DeleteQuickFix(const std::string & bundleName,std::shared_ptr<QuickFixResult> & quickFixRes)3282 ErrCode BundleTestTool::DeleteQuickFix(const std::string &bundleName,
3283     std::shared_ptr<QuickFixResult> &quickFixRes)
3284 {
3285     APP_LOGD("DeleteQuickFix bundleName: %{public}s", bundleName.c_str());
3286 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3287     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3288     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3289         APP_LOGE("callback or bundleMgrProxy is null");
3290         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3291     }
3292     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3293     if (recipient == nullptr) {
3294         APP_LOGE("recipient is null");
3295         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3296     }
3297     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3298     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3299     if (quickFixProxy == nullptr) {
3300         APP_LOGE("quickFixProxy is null");
3301         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3302     }
3303     auto res = quickFixProxy->DeleteQuickFix(bundleName, callback);
3304     if (res != ERR_OK) {
3305         APP_LOGE("DeleteQuickFix failed");
3306         return res;
3307     }
3308     return callback->GetResultCode(quickFixRes);
3309 #else
3310     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3311 #endif
3312 }
3313 
GetResMsg(int32_t code)3314 std::string BundleTestTool::GetResMsg(int32_t code)
3315 {
3316     std::unordered_map<int32_t, std::string> quickFixMsgMap;
3317     CreateQuickFixMsgMap(quickFixMsgMap);
3318     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
3319         return quickFixMsgMap.at(code);
3320     }
3321     return MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
3322 }
3323 
GetResMsg(int32_t code,const std::shared_ptr<QuickFixResult> & quickFixRes)3324 std::string BundleTestTool::GetResMsg(int32_t code, const std::shared_ptr<QuickFixResult> &quickFixRes)
3325 {
3326     std::string resMsg;
3327     std::unordered_map<int32_t, std::string> quickFixMsgMap;
3328     CreateQuickFixMsgMap(quickFixMsgMap);
3329     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
3330         resMsg += quickFixMsgMap.at(code);
3331     } else {
3332         resMsg += MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
3333     }
3334     if (quickFixRes != nullptr) {
3335         resMsg += quickFixRes->ToString() + "\n";
3336     }
3337     return resMsg;
3338 }
3339 
RunAsSetDebugMode()3340 ErrCode BundleTestTool::RunAsSetDebugMode()
3341 {
3342     int32_t result = OHOS::ERR_OK;
3343     int32_t counter = 0;
3344     int32_t enable = -1;
3345     while (true) {
3346         counter++;
3347         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_DEBUG_MODE.c_str(), LONG_OPTIONS_DEBUG_MODE, nullptr);
3348         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3349         if (optind < 0 || optind > argc_) {
3350             return OHOS::ERR_INVALID_VALUE;
3351         }
3352 
3353         if (option == -1 || option == '?') {
3354             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3355                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3356                 result = OHOS::ERR_INVALID_VALUE;
3357                 break;
3358             }
3359             if (optopt == 'e') {
3360                 // 'bundle_test_tool setDebugMode -e' with no argument
3361                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3362                 result = OHOS::ERR_INVALID_VALUE;
3363                 break;
3364             }
3365             break;
3366         }
3367 
3368         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
3369             APP_LOGD("'bundle_test_tool setDebugMode -e %{public}s'", argv_[optind - 1]);
3370             continue;
3371         }
3372         result = OHOS::ERR_INVALID_VALUE;
3373         break;
3374     }
3375 
3376     if (result != OHOS::ERR_OK) {
3377         resultReceiver_.append(HELP_MSG_SET_DEBUG_MODE);
3378         return result;
3379     }
3380     ErrCode setResult = SetDebugMode(enable);
3381     if (setResult == OHOS::ERR_OK) {
3382         resultReceiver_ = STRING_SET_DEBUG_MODE_OK;
3383     } else {
3384         resultReceiver_ = STRING_SET_DEBUG_MODE_NG + GetResMsg(setResult);
3385     }
3386     return setResult;
3387 }
3388 
SetDebugMode(int32_t debugMode)3389 ErrCode BundleTestTool::SetDebugMode(int32_t debugMode)
3390 {
3391     if (debugMode != 0 && debugMode != 1) {
3392         APP_LOGE("SetDebugMode param is invalid");
3393         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM;
3394     }
3395     bool enable = debugMode == 0 ? false : true;
3396     if (bundleMgrProxy_ == nullptr) {
3397         APP_LOGE("bundleMgrProxy_ is nullptr");
3398         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR;
3399     }
3400     return bundleMgrProxy_->SetDebugMode(enable);
3401 }
3402 
BundleNameAndUserIdCommonFunc(std::string & bundleName,int32_t & userId,int32_t & appIndex)3403 ErrCode BundleTestTool::BundleNameAndUserIdCommonFunc(std::string &bundleName, int32_t &userId, int32_t &appIndex)
3404 {
3405     int32_t result = OHOS::ERR_OK;
3406     int32_t counter = 0;
3407     userId = Constants::UNSPECIFIED_USERID;
3408     while (true) {
3409         counter++;
3410         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLE_STATS.c_str(),
3411             LONG_OPTIONS_GET_BUNDLE_STATS, nullptr);
3412         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3413         if (optind < 0 || optind > argc_) {
3414             return OHOS::ERR_INVALID_VALUE;
3415         }
3416         if (option == -1) {
3417             if (counter == 1) {
3418                 // When scanning the first argument
3419                 if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
3420                     resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3421                     result = OHOS::ERR_INVALID_VALUE;
3422                 }
3423             }
3424             break;
3425         }
3426 
3427         if (option == '?') {
3428             switch (optopt) {
3429                 case 'n': {
3430                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3431                     result = OHOS::ERR_INVALID_VALUE;
3432                     break;
3433                 }
3434                 case 'u': {
3435                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3436                     result = OHOS::ERR_INVALID_VALUE;
3437                     break;
3438                 }
3439                 case 'a': {
3440                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3441                     result = OHOS::ERR_INVALID_VALUE;
3442                     break;
3443                 }
3444                 default: {
3445                     std::string unknownOption = "";
3446                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3447                     resultReceiver_.append(unknownOptionMsg);
3448                     result = OHOS::ERR_INVALID_VALUE;
3449                     break;
3450                 }
3451             }
3452             break;
3453         }
3454 
3455         switch (option) {
3456             case 'h': {
3457                 result = OHOS::ERR_INVALID_VALUE;
3458                 break;
3459             }
3460             case 'n': {
3461                 bundleName = optarg;
3462                 break;
3463             }
3464             case 'u': {
3465                 if (!OHOS::StrToInt(optarg, userId) || userId < 0) {
3466                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3467                     return OHOS::ERR_INVALID_VALUE;
3468                 }
3469                 break;
3470             }
3471             case 'a': {
3472                 if (!OHOS::StrToInt(optarg, appIndex) || (appIndex < 0 || appIndex > INITIAL_SANDBOX_APP_INDEX)) {
3473                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3474                     return OHOS::ERR_INVALID_VALUE;
3475                 }
3476                 break;
3477             }
3478             default: {
3479                 result = OHOS::ERR_INVALID_VALUE;
3480                 break;
3481             }
3482         }
3483     }
3484 
3485     if (result == OHOS::ERR_OK) {
3486         if (resultReceiver_ == "" && bundleName.size() == 0) {
3487             resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION + "\n");
3488             result = OHOS::ERR_INVALID_VALUE;
3489         }
3490     }
3491     return result;
3492 }
3493 
RunAsGetBundleStats()3494 ErrCode BundleTestTool::RunAsGetBundleStats()
3495 {
3496     std::string bundleName;
3497     int32_t userId;
3498     int32_t appIndex = 0;
3499     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3500     if (result != OHOS::ERR_OK) {
3501         resultReceiver_.append(HELP_MSG_GET_BUNDLE_STATS);
3502     } else {
3503         std::string msg;
3504         bool ret = GetBundleStats(bundleName, userId, msg, appIndex);
3505         if (ret) {
3506             resultReceiver_ = STRING_GET_BUNDLE_STATS_OK + msg;
3507         } else {
3508             resultReceiver_ = STRING_GET_BUNDLE_STATS_NG + "\n";
3509         }
3510     }
3511 
3512     return result;
3513 }
3514 
GetBundleStats(const std::string & bundleName,int32_t userId,std::string & msg,int32_t appIndex)3515 bool BundleTestTool::GetBundleStats(const std::string &bundleName, int32_t userId,
3516     std::string& msg, int32_t appIndex)
3517 {
3518     if (bundleMgrProxy_ == nullptr) {
3519         APP_LOGE("bundleMgrProxy_ is nullptr");
3520         return false;
3521     }
3522     userId = BundleCommandCommon::GetCurrentUserId(userId);
3523     std::vector<std::int64_t> bundleStats;
3524     bool ret = bundleMgrProxy_->GetBundleStats(bundleName, userId, bundleStats, appIndex);
3525     if (ret) {
3526         for (size_t index = 0; index < bundleStats.size(); ++index) {
3527             msg += GET_BUNDLE_STATS_ARRAY[index] + std::to_string(bundleStats[index]) + "\n";
3528         }
3529     }
3530     return ret;
3531 }
3532 
RunAsGetAppProvisionInfo()3533 ErrCode BundleTestTool::RunAsGetAppProvisionInfo()
3534 {
3535     std::string bundleName;
3536     int32_t userId;
3537     int32_t appIndex = 0;
3538     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3539     if (result != OHOS::ERR_OK) {
3540         resultReceiver_.append(HELP_MSG_GET_APP_PROVISION_INFO);
3541     } else {
3542         std::string msg;
3543         result = GetAppProvisionInfo(bundleName, userId, msg);
3544         if (result == OHOS::ERR_OK) {
3545             resultReceiver_ = STRING_GET_APP_PROVISION_INFO_OK + msg;
3546         } else {
3547             resultReceiver_ = STRING_GET_APP_PROVISION_INFO_NG + "\n";
3548         }
3549     }
3550 
3551     return result;
3552 }
3553 
GetAppProvisionInfo(const std::string & bundleName,int32_t userId,std::string & msg)3554 ErrCode BundleTestTool::GetAppProvisionInfo(const std::string &bundleName,
3555     int32_t userId, std::string& msg)
3556 {
3557     if (bundleMgrProxy_ == nullptr) {
3558         APP_LOGE("bundleMgrProxy_ is nullptr");
3559         return OHOS::ERR_INVALID_VALUE;
3560     }
3561     userId = BundleCommandCommon::GetCurrentUserId(userId);
3562     AppProvisionInfo info;
3563     auto ret = bundleMgrProxy_->GetAppProvisionInfo(bundleName, userId, info);
3564     if (ret == ERR_OK) {
3565         msg = "{\n";
3566         msg += "    versionCode: " + std::to_string(info.versionCode) + "\n";
3567         msg += "    versionName: " + info.versionName+ "\n";
3568         msg += "    uuid: " + info.uuid + "\n";
3569         msg += "    type: " + info.type + "\n";
3570         msg += "    appDistributionType: " + info.appDistributionType + "\n";
3571         msg += "    developerId: " + info.developerId + "\n";
3572         msg += "    certificate: " + info.certificate + "\n";
3573         msg += "    apl: " + info.apl + "\n";
3574         msg += "    issuer: " + info.issuer + "\n";
3575         msg += "    validity: {\n";
3576         msg += "        notBefore: " + std::to_string(info.validity.notBefore) + "\n";
3577         msg += "        notAfter: " + std::to_string(info.validity.notAfter) + "\n";
3578         msg += "    }\n";
3579         msg += "    appServiceCapabilities: " + info.appServiceCapabilities + "\n";
3580         msg += "}\n";
3581     }
3582     return ret;
3583 }
3584 
RunAsGetDistributedBundleName()3585 ErrCode BundleTestTool::RunAsGetDistributedBundleName()
3586 {
3587     ErrCode result;
3588     std::string networkId;
3589     int32_t counter = 0;
3590     int32_t accessTokenId = 0;
3591     while (true) {
3592         counter++;
3593         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME.c_str(),
3594             LONG_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME, nullptr);
3595         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3596         if (optind < 0 || optind > argc_) {
3597             return OHOS::ERR_INVALID_VALUE;
3598         }
3599         if (option == -1) {
3600             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3601                 resultReceiver_.append(HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION);
3602                 return OHOS::ERR_INVALID_VALUE;
3603             }
3604             break;
3605         }
3606         result = CheckGetDistributedBundleNameCorrectOption(option, GET_DISTRIBUTED_BUNDLE_NAME_COMMAND_NAME,
3607             networkId, accessTokenId);
3608         if (result != OHOS::ERR_OK) {
3609             resultReceiver_.append(HELP_MSG_GET_DISTRIBUTED_BUNDLE_NAME);
3610             return OHOS::ERR_INVALID_VALUE;
3611         }
3612     }
3613     if (accessTokenId == 0 || networkId.size() == 0) {
3614         resultReceiver_.append(HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION);
3615         return OHOS::ERR_INVALID_VALUE;
3616     }
3617     std::string msg;
3618     result = GetDistributedBundleName(networkId, accessTokenId, msg);
3619     if (result == OHOS::ERR_OK) {
3620         resultReceiver_ = STRING_GET_DISTRIBUTED_BUNDLE_NAME_OK + msg;
3621     } else {
3622         resultReceiver_ = STRING_GET_DISTRIBUTED_BUNDLE_NAME_NG + "\n";
3623         APP_LOGE("RunAsGetDistributedBundleName fail result %{public}d.", result);
3624     }
3625     return result;
3626 }
3627 
CheckGetDistributedBundleNameCorrectOption(int32_t option,const std::string & commandName,std::string & networkId,int32_t & accessTokenId)3628 ErrCode BundleTestTool::CheckGetDistributedBundleNameCorrectOption(int32_t option, const std::string &commandName,
3629     std::string &networkId, int32_t &accessTokenId)
3630 {
3631     ErrCode result = OHOS::ERR_OK;
3632     switch (option) {
3633         case 'h': {
3634             result = OHOS::ERR_INVALID_VALUE;
3635             break;
3636         }
3637         case 'n': {
3638             networkId = optarg;
3639             if (networkId.size() == 0) {
3640                 return OHOS::ERR_INVALID_VALUE;
3641             }
3642             break;
3643         }
3644         case 'a': {
3645             if (!OHOS::StrToInt(optarg, accessTokenId) || accessTokenId < 0) {
3646                 return OHOS::ERR_INVALID_VALUE;
3647             }
3648             break;
3649         }
3650         default: {
3651             result = OHOS::ERR_INVALID_VALUE;
3652             break;
3653         }
3654     }
3655     return result;
3656 }
3657 
GetDistributedBundleName(const std::string & networkId,int32_t accessTokenId,std::string & msg)3658 ErrCode BundleTestTool::GetDistributedBundleName(const std::string &networkId,
3659     int32_t accessTokenId, std::string& msg)
3660 {
3661 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
3662     if (distributedBmsProxy_ == nullptr) {
3663         APP_LOGE("distributedBmsProxy_ is nullptr");
3664         return OHOS::ERR_INVALID_VALUE;
3665     }
3666     std::string bundleName;
3667     auto ret = distributedBmsProxy_->GetDistributedBundleName(networkId, accessTokenId, bundleName);
3668     if (ret == OHOS::NO_ERROR) {
3669         msg = "\n";
3670         if (bundleName.size() == 0) {
3671             msg += "no match found \n";
3672         } else {
3673             msg += bundleName + "\n";
3674         }
3675         msg += "\n";
3676     } else {
3677         APP_LOGE("distributedBmsProxy_ GetDistributedBundleName fail errcode %{public}d.", ret);
3678         return OHOS::ERR_INVALID_VALUE;
3679     }
3680     return OHOS::ERR_OK;
3681 #else
3682     return OHOS::ERR_INVALID_VALUE;
3683 #endif
3684 }
3685 
ParseEventCallbackOptions(bool & onlyUnregister,int32_t & uid)3686 bool BundleTestTool::ParseEventCallbackOptions(bool &onlyUnregister, int32_t &uid)
3687 {
3688     int32_t opt;
3689     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_BUNDLE_EVENT_CALLBACK.c_str(),
3690         LONG_OPTIONS_BUNDLE_EVENT_CALLBACK, nullptr)) != -1) {
3691         switch (opt) {
3692             case 'o': {
3693                 onlyUnregister = true;
3694                 break;
3695             }
3696             case 'u': {
3697                 if (!OHOS::StrToInt(optarg, uid)) {
3698                     std::string msg = "invalid param, uid should be int";
3699                     resultReceiver_.append(msg).append(LINE_BREAK);
3700                     APP_LOGE("%{public}s", msg.c_str());
3701                     return false;
3702                 }
3703                 break;
3704             }
3705             case 'h': {
3706                 resultReceiver_.append(HELP_MSG_BUNDLE_EVENT_CALLBACK);
3707                 return false;
3708             }
3709             default: {
3710                 std::string msg = "unsupported option";
3711                 resultReceiver_.append(msg).append(LINE_BREAK);
3712                 APP_LOGE("%{public}s", msg.c_str());
3713                 return false;
3714             }
3715         }
3716     }
3717     APP_LOGI("ParseEventCallbackOptions success");
3718     return true;
3719 }
3720 
ParseResetAOTCompileStatusOptions(std::string & bundleName,std::string & moduleName,int32_t & triggerMode,int32_t & uid)3721 bool BundleTestTool::ParseResetAOTCompileStatusOptions(std::string &bundleName, std::string &moduleName,
3722     int32_t &triggerMode, int32_t &uid)
3723 {
3724     int32_t opt;
3725     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_RESET_AOT_COMPILE_StATUS.c_str(),
3726         LONG_OPTIONS_RESET_AOT_COMPILE_StATUS, nullptr)) != -1) {
3727         switch (opt) {
3728             case 'b': {
3729                 bundleName = optarg;
3730                 break;
3731             }
3732             case 'm': {
3733                 moduleName = optarg;
3734                 break;
3735             }
3736             case 't': {
3737                 if (!OHOS::StrToInt(optarg, triggerMode)) {
3738                     std::string msg = "invalid param, triggerMode should be int";
3739                     resultReceiver_.append(msg).append(LINE_BREAK);
3740                     APP_LOGE("%{public}s", msg.c_str());
3741                     return false;
3742                 }
3743                 break;
3744             }
3745             case 'u': {
3746                 if (!OHOS::StrToInt(optarg, uid)) {
3747                     std::string msg = "invalid param, uid should be int";
3748                     resultReceiver_.append(msg).append(LINE_BREAK);
3749                     APP_LOGE("%{public}s", msg.c_str());
3750                     return false;
3751                 }
3752                 break;
3753             }
3754             case 'h': {
3755                 resultReceiver_.append(HELP_MSG_RESET_AOT_COMPILE_StATUS);
3756                 return false;
3757             }
3758             default: {
3759                 std::string msg = "unsupported option";
3760                 resultReceiver_.append(msg).append(LINE_BREAK);
3761                 APP_LOGE("%{public}s", msg.c_str());
3762                 return false;
3763             }
3764         }
3765     }
3766     APP_LOGI("ParseResetAOTCompileStatusOptions success");
3767     return true;
3768 }
3769 
Sleep(int32_t seconds)3770 void BundleTestTool::Sleep(int32_t seconds)
3771 {
3772     APP_LOGI("begin to sleep %{public}d seconds", seconds);
3773     std::this_thread::sleep_for(std::chrono::seconds(seconds));
3774     APP_LOGI("sleep done");
3775 }
3776 
CallRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)3777 ErrCode BundleTestTool::CallRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)
3778 {
3779     APP_LOGI("begin to call RegisterBundleEventCallback");
3780     std::string msg;
3781     bool ret = bundleMgrProxy_->RegisterBundleEventCallback(bundleEventCallback);
3782     if (!ret) {
3783         msg = "RegisterBundleEventCallback failed";
3784         resultReceiver_.append(msg).append(LINE_BREAK);
3785         APP_LOGE("%{public}s", msg.c_str());
3786         return OHOS::ERR_INVALID_VALUE;
3787     }
3788     msg = "RegisterBundleEventCallback success";
3789     resultReceiver_.append(msg).append(LINE_BREAK);
3790     APP_LOGI("%{public}s", msg.c_str());
3791     return OHOS::ERR_OK;
3792 }
3793 
CallUnRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)3794 ErrCode BundleTestTool::CallUnRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)
3795 {
3796     APP_LOGI("begin to call UnregisterBundleEventCallback");
3797     std::string msg;
3798     bool ret = bundleMgrProxy_->UnregisterBundleEventCallback(bundleEventCallback);
3799     if (!ret) {
3800         msg = "UnregisterBundleEventCallback failed";
3801         resultReceiver_.append(msg).append(LINE_BREAK);
3802         APP_LOGE("%{public}s", msg.c_str());
3803         return OHOS::ERR_INVALID_VALUE;
3804     }
3805     msg = "UnregisterBundleEventCallback success";
3806     resultReceiver_.append(msg).append(LINE_BREAK);
3807     APP_LOGI("%{public}s", msg.c_str());
3808     return OHOS::ERR_OK;
3809 }
3810 
HandleBundleEventCallback()3811 ErrCode BundleTestTool::HandleBundleEventCallback()
3812 {
3813     APP_LOGI("begin to HandleBundleEventCallback");
3814     bool onlyUnregister = false;
3815     int32_t uid = Constants::FOUNDATION_UID;
3816     if (!ParseEventCallbackOptions(onlyUnregister, uid)) {
3817         APP_LOGE("ParseEventCallbackOptions failed");
3818         return OHOS::ERR_INVALID_VALUE;
3819     }
3820     APP_LOGI("onlyUnregister : %{public}d, uid : %{public}d", onlyUnregister, uid);
3821     if (bundleMgrProxy_ == nullptr) {
3822         std::string msg = "bundleMgrProxy_ is nullptr";
3823         resultReceiver_.append(msg).append(LINE_BREAK);
3824         APP_LOGE("%{public}s", msg.c_str());
3825         return OHOS::ERR_INVALID_VALUE;
3826     }
3827     seteuid(uid);
3828     ErrCode ret;
3829     sptr<BundleEventCallbackImpl> bundleEventCallback = new (std::nothrow) BundleEventCallbackImpl();
3830     if (onlyUnregister) {
3831         // only call UnRegisterBundleEventCallback
3832         return CallUnRegisterBundleEventCallback(bundleEventCallback);
3833     }
3834     // call RegisterBundleEventCallback then call UnRegisterBundleEventCallback
3835     ret = CallRegisterBundleEventCallback(bundleEventCallback);
3836     if (ret != OHOS::ERR_OK) {
3837         return ret;
3838     }
3839     Sleep(SLEEP_SECONDS);
3840     ret = CallUnRegisterBundleEventCallback(bundleEventCallback);
3841     if (ret != OHOS::ERR_OK) {
3842         return ret;
3843     }
3844     Sleep(SLEEP_SECONDS);
3845     return OHOS::ERR_OK;
3846 }
3847 
ResetAOTCompileStatus()3848 ErrCode BundleTestTool::ResetAOTCompileStatus()
3849 {
3850     APP_LOGI("begin to ResetAOTCompileStatus");
3851     std::string bundleName;
3852     std::string moduleName;
3853     int32_t triggerMode = 0;
3854     int32_t uid = -1;
3855     if (!ParseResetAOTCompileStatusOptions(bundleName, moduleName, triggerMode, uid)) {
3856         APP_LOGE("ParseResetAOTCompileStatusOptions failed");
3857         return OHOS::ERR_INVALID_VALUE;
3858     }
3859     APP_LOGI("bundleName : %{public}s, moduleName : %{public}s, triggerMode : %{public}d",
3860         bundleName.c_str(), moduleName.c_str(), triggerMode);
3861     if (bundleMgrProxy_ == nullptr) {
3862         std::string msg = "bundleMgrProxy_ is nullptr";
3863         resultReceiver_.append(msg).append(LINE_BREAK);
3864         APP_LOGE("%{public}s", msg.c_str());
3865         return OHOS::ERR_INVALID_VALUE;
3866     }
3867     if (uid == -1) {
3868         int32_t userId = 100;
3869         uid = bundleMgrProxy_->GetUidByBundleName(bundleName, userId);
3870     }
3871     APP_LOGI("uid : %{public}d", uid);
3872     seteuid(uid);
3873     ErrCode ret = bundleMgrProxy_->ResetAOTCompileStatus(bundleName, moduleName, triggerMode);
3874     APP_LOGI("ret : %{public}d", ret);
3875     return OHOS::ERR_OK;
3876 }
3877 
SendCommonEvent()3878 ErrCode BundleTestTool::SendCommonEvent()
3879 {
3880     APP_LOGI("begin to SendCommonEvent");
3881     OHOS::AAFwk::Want want;
3882     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED);
3883     EventFwk::CommonEventData commonData { want };
3884     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
3885     return OHOS::ERR_OK;
3886 }
3887 
RunAsQueryDataGroupInfos()3888 ErrCode BundleTestTool::RunAsQueryDataGroupInfos()
3889 {
3890     APP_LOGI("RunAsQueryDataGroupInfos start");
3891     std::string bundleName;
3892     int32_t userId;
3893     int32_t appIndex;
3894     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3895     if (result != OHOS::ERR_OK) {
3896         resultReceiver_.append(HELP_MSG_QUERY_DATA_GROUP_INFOS);
3897     } else {
3898         std::string msg;
3899         result = QueryDataGroupInfos(bundleName, userId, msg);
3900         if (result) {
3901             resultReceiver_ = STRING_QUERY_DATA_GROUP_INFOS_OK + msg;
3902             return ERR_OK;
3903         } else {
3904             resultReceiver_ = STRING_QUERY_DATA_GROUP_INFOS_NG + "\n";
3905         }
3906     }
3907     return OHOS::ERR_INVALID_VALUE;
3908 }
3909 
QueryDataGroupInfos(const std::string & bundleName,int32_t userId,std::string & msg)3910 bool BundleTestTool::QueryDataGroupInfos(const std::string &bundleName,
3911     int32_t userId, std::string& msg)
3912 {
3913     if (bundleMgrProxy_ == nullptr) {
3914         APP_LOGE("bundleMgrProxy_ is nullptr");
3915         return OHOS::ERR_INVALID_VALUE;
3916     }
3917     std::vector<DataGroupInfo> infos;
3918     bool ret = bundleMgrProxy_->QueryDataGroupInfos(bundleName, userId, infos);
3919     if (ret) {
3920         msg = "dataGroupInfos:\n{\n";
3921         for (const auto &dataGroupInfo : infos) {
3922             msg +="     ";
3923             msg += dataGroupInfo.ToString();
3924             msg += "\n";
3925         }
3926         msg += "}\n";
3927         return true;
3928     }
3929 
3930     return false;
3931 }
3932 
RunAsGetGroupDir()3933 ErrCode BundleTestTool::RunAsGetGroupDir()
3934 {
3935     APP_LOGI("RunAsGetGroupDir start");
3936     ErrCode result;
3937     std::string dataGroupId;
3938     int32_t counter = 0;
3939     while (true) {
3940         counter++;
3941         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_GROUP_DIR.c_str(),
3942             LONG_OPTIONS_GET_GROUP_DIR, nullptr);
3943         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3944         if (optind < 0 || optind > argc_) {
3945             return OHOS::ERR_INVALID_VALUE;
3946         }
3947         if (option == -1) {
3948             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3949                 resultReceiver_.append(HELP_MSG_GET_GROUP_DIR);
3950                 return OHOS::ERR_INVALID_VALUE;
3951             }
3952             break;
3953         }
3954         result = CheckGetGroupIdCorrectOption(option, dataGroupId);
3955         if (result != OHOS::ERR_OK) {
3956             resultReceiver_.append(HELP_MSG_GET_GROUP_DIR);
3957             return OHOS::ERR_INVALID_VALUE;
3958         }
3959     }
3960     std::string msg;
3961     bool ret = GetGroupDir(dataGroupId, msg);
3962     if (ret) {
3963         resultReceiver_ = STRING_GET_GROUP_DIR_OK + msg;
3964     } else {
3965         resultReceiver_ = STRING_GET_GROUP_DIR_NG + "\n";
3966         APP_LOGE("RunAsGetGroupDir fail");
3967         return OHOS::ERR_INVALID_VALUE;
3968     }
3969     return result;
3970 }
3971 
CheckGetGroupIdCorrectOption(int32_t option,std::string & dataGroupId)3972 ErrCode BundleTestTool::CheckGetGroupIdCorrectOption(int32_t option, std::string &dataGroupId)
3973 {
3974     ErrCode result = OHOS::ERR_OK;
3975     switch (option) {
3976         case 'h': {
3977             result = OHOS::ERR_INVALID_VALUE;
3978             break;
3979         }
3980         case 'd': {
3981             dataGroupId = optarg;
3982             if (dataGroupId.size() == 0) {
3983                 return OHOS::ERR_INVALID_VALUE;
3984             }
3985             break;
3986         }
3987         default: {
3988             result = OHOS::ERR_INVALID_VALUE;
3989             break;
3990         }
3991     }
3992     return result;
3993 }
3994 
GetGroupDir(const std::string & dataGroupId,std::string & msg)3995 bool BundleTestTool::GetGroupDir(const std::string &dataGroupId, std::string& msg)
3996 {
3997     if (bundleMgrProxy_ == nullptr) {
3998         APP_LOGE("bundleMgrProxy_ is nullptr");
3999         return OHOS::ERR_INVALID_VALUE;
4000     }
4001     std::string dir;
4002     bool ret = bundleMgrProxy_->GetGroupDir(dataGroupId, dir);
4003     if (ret) {
4004         msg = "group dir:\n";
4005         msg += dir;
4006         msg += "\n";
4007         return true;
4008     }
4009 
4010     return false;
4011 }
4012 
CheckGetBundleNameOption(int32_t option,std::string & bundleName)4013 ErrCode BundleTestTool::CheckGetBundleNameOption(int32_t option, std::string &bundleName)
4014 {
4015     ErrCode result = OHOS::ERR_OK;
4016     switch (option) {
4017         case 'h': {
4018             result = OHOS::ERR_INVALID_VALUE;
4019             break;
4020         }
4021         case 'n': {
4022             bundleName = optarg;
4023             if (bundleName.size() == 0) {
4024                 return OHOS::ERR_INVALID_VALUE;
4025             }
4026             break;
4027         }
4028         default: {
4029             result = OHOS::ERR_INVALID_VALUE;
4030             break;
4031         }
4032     }
4033     return result;
4034 }
4035 
RunAsGetJsonProfile()4036 ErrCode BundleTestTool::RunAsGetJsonProfile()
4037 {
4038     APP_LOGI("RunAsGetJsonProfile start");
4039     int result = OHOS::ERR_OK;
4040     int counter = 0;
4041     std::string commandName = "getJsonProfile";
4042     std::string name = "";
4043     std::string bundleName = "";
4044     std::string moduleName = "";
4045     int jsonProfileType = -1;
4046     int userId = 100;
4047     APP_LOGD("RunAsGetStringCommand is start");
4048     while (true) {
4049         counter++;
4050         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_JSON_PROFILE.c_str(),
4051             LONG_OPTIONS_GET_JSON_PROFILE, nullptr);
4052         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4053         if (optind < 0 || optind > argc_) {
4054             return OHOS::ERR_INVALID_VALUE;
4055         }
4056         if (option == -1) {
4057             // When scanning the first argument
4058             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4059                 // 'GetStringById' with no option: GetStringById
4060                 // 'GetStringById' with a wrong argument: GetStringById
4061                 APP_LOGD("bundle_test_tool getStr with no option.");
4062                 resultReceiver_.append(HELP_MSG_NO_GET_JSON_PROFILE_OPTION);
4063                 return OHOS::ERR_INVALID_VALUE;
4064             }
4065             break;
4066         }
4067         int temp = 0;
4068         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4069             ? OHOS::ERR_INVALID_VALUE : result;
4070         moduleName = option == 'm' ? name : moduleName;
4071         bundleName = option == 'n' ? name : bundleName;
4072         userId = option == 'u' ? temp : userId;
4073         jsonProfileType = option == 'p' ? temp : jsonProfileType;
4074     }
4075 
4076     if (result != OHOS::ERR_OK) {
4077         resultReceiver_.append(HELP_MSG_GET_STRING);
4078     } else {
4079         std::string results = "";
4080         auto res = bundleMgrProxy_->GetJsonProfile(static_cast<ProfileType>(jsonProfileType),
4081             bundleName, moduleName, results, userId);
4082         if (res != OHOS::ERR_OK || results.empty()) {
4083             resultReceiver_.append(STRING_GET_JSON_PROFILE_NG);
4084             return result;
4085         }
4086         resultReceiver_.append(results);
4087         resultReceiver_.append("\n");
4088     }
4089     return result;
4090 }
4091 
RunGetUidByBundleName()4092 ErrCode BundleTestTool::RunGetUidByBundleName()
4093 {
4094     APP_LOGI("RunGetUidByBundleName start");
4095     int result = OHOS::ERR_OK;
4096     int counter = 0;
4097     std::string name = "";
4098     std::string commandName = "getUidByBundleName";
4099     std::string bundleName = "";
4100     int userId = 100;
4101     int appIndex = 0;
4102     APP_LOGD("RunGetIntCommand is start");
4103     bool flag = true;
4104     while (flag) {
4105         counter++;
4106         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_UID_BY_BUNDLENAME.c_str(),
4107             LONG_OPTIONS_GET_UID_BY_BUNDLENAME, nullptr);
4108         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4109         if (optind < 0 || optind > argc_) {
4110             return OHOS::ERR_INVALID_VALUE;
4111         }
4112         if (option == -1) {
4113             // When scanning the first argument
4114             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4115                 APP_LOGD("bundle_test_tool getUidByBundleName with no option.");
4116                 resultReceiver_.append(HELP_MSG_NO_GET_UID_BY_BUNDLENAME);
4117                 return OHOS::ERR_INVALID_VALUE;
4118             }
4119             break;
4120         }
4121         int temp = 0;
4122         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4123             ? OHOS::ERR_INVALID_VALUE : result;
4124         bundleName = option == 'n' ? name : bundleName;
4125         userId = option == 'u' ? temp : userId;
4126         appIndex = option == 'a' ? temp : appIndex;
4127     }
4128 
4129     if (result != OHOS::ERR_OK) {
4130         resultReceiver_.append(HELP_MSG_NO_GET_UID_BY_BUNDLENAME);
4131     } else {
4132         int32_t res = bundleMgrProxy_->GetUidByBundleName(bundleName, userId, appIndex);
4133         if (res == -1) {
4134             resultReceiver_.append(STRING_GET_UID_BY_BUNDLENAME_NG);
4135             return result;
4136         }
4137         resultReceiver_.append(std::to_string(res));
4138         resultReceiver_.append("\n");
4139     }
4140     return result;
4141 }
4142 
RunAsGetUninstalledBundleInfo()4143 ErrCode BundleTestTool::RunAsGetUninstalledBundleInfo()
4144 {
4145     APP_LOGI("RunAsGetUninstalledBundleInfo start");
4146     int result = OHOS::ERR_OK;
4147     int counter = 0;
4148     std::string bundleName = "";
4149     while (true) {
4150         counter++;
4151         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_UNINSTALLED_BUNDLE_INFO.c_str(),
4152             LONG_OPTIONS_UNINSTALLED_BUNDLE_INFO, nullptr);
4153         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4154         if (optind < 0 || optind > argc_) {
4155             return OHOS::ERR_INVALID_VALUE;
4156         }
4157         if (option == -1) {
4158             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4159                 resultReceiver_.append(HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION);
4160                 return OHOS::ERR_INVALID_VALUE;
4161             }
4162             break;
4163         }
4164         result = CheckGetBundleNameOption(option, bundleName);
4165         APP_LOGD("getUninstalledBundleInfo optind: %{public}s", bundleName.c_str());
4166     }
4167 
4168     if (result != OHOS::ERR_OK) {
4169         resultReceiver_.append(HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION);
4170     } else {
4171         BundleInfo bundleInfo;
4172         auto res = bundleMgrProxy_->GetUninstalledBundleInfo(bundleName, bundleInfo);
4173         if (res != OHOS::ERR_OK) {
4174             resultReceiver_.append(STRING_GET_UNINSTALLED_BUNDLE_INFO_NG);
4175             return result;
4176         }
4177         nlohmann::json jsonObject = bundleInfo;
4178         jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
4179         std::string results = jsonObject.dump(Constants::DUMP_INDENT);
4180         resultReceiver_.append(results);
4181         resultReceiver_.append("\n");
4182     }
4183     return result;
4184 }
4185 
RunAsGetOdid()4186 ErrCode BundleTestTool::RunAsGetOdid()
4187 {
4188     std::string commandName = "getOdid";
4189     int uid = Constants::INVALID_UID;
4190     int opt = 0;
4191 
4192     const std::map<char, OptionHandler> getOdidOptionHandlers = {
4193         {'u', [&uid, &commandName, this](const std::string& value) {
4194             bool ret;
4195             StringToInt(value, commandName, uid, ret); }}
4196     };
4197     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_ODID.c_str(), LONG_OPTIONS_GET_ODID, nullptr)) != -1) {
4198         auto it = getOdidOptionHandlers.find(opt);
4199         if (it != getOdidOptionHandlers.end()) {
4200             it->second(optarg);
4201         } else {
4202             resultReceiver_.append(HELP_MSG_GET_ODID);
4203             return OHOS::ERR_INVALID_VALUE;
4204         }
4205     }
4206     std::string odid;
4207     setuid(uid);
4208     auto result = bundleMgrProxy_->GetOdid(odid);
4209     setuid(Constants::ROOT_UID);
4210     if (result == ERR_OK) {
4211         resultReceiver_.append(STRING_GET_ODID_OK);
4212         resultReceiver_.append(odid + "\n");
4213     } else if (result == ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST) {
4214         resultReceiver_.append(STRING_GET_ODID_NG + "Please enter a valid uid\n");
4215     } else {
4216         resultReceiver_.append(STRING_GET_ODID_NG + "errCode is "+ std::to_string(result) + "\n");
4217     }
4218     return result;
4219 }
4220 
CheckImplicitQueryWantOption(int option,std::string & value)4221 ErrCode BundleTestTool::CheckImplicitQueryWantOption(int option, std::string &value)
4222 {
4223     ErrCode result = OHOS::ERR_OK;
4224     switch (option) {
4225         case 'n': {
4226             value = optarg;
4227             break;
4228         }
4229         case 'a': {
4230             value = optarg;
4231             break;
4232         }
4233         case 'e': {
4234             value = optarg;
4235             break;
4236         }
4237         case 'u': {
4238             value = optarg;
4239             break;
4240         }
4241         case 't': {
4242             value = optarg;
4243             break;
4244         }
4245         default: {
4246             std::string unknownOption = "";
4247             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
4248             resultReceiver_.append(unknownOptionMsg);
4249             result = OHOS::ERR_INVALID_VALUE;
4250             break;
4251         }
4252     }
4253     return result;
4254 }
4255 
ImplicitQuerySkillUriInfo(const std::string & bundleName,const std::string & action,const std::string & entity,const std::string & uri,const std::string & type,std::string & msg)4256 ErrCode BundleTestTool::ImplicitQuerySkillUriInfo(const std::string &bundleName,
4257     const std::string &action, const std::string &entity, const std::string &uri,
4258     const std::string &type, std::string &msg)
4259 {
4260     if (bundleMgrProxy_ == nullptr) {
4261         APP_LOGE("bundleMgrProxy_ is nullptr");
4262         return OHOS::ERR_INVALID_VALUE;
4263     }
4264     AAFwk::Want want;
4265     want.SetAction(action);
4266     want.AddEntity(entity);
4267     ElementName elementName("", bundleName, "", "");
4268     want.SetElement(elementName);
4269     want.SetUri(uri);
4270     want.SetType(type);
4271 
4272     int32_t userId = BundleCommandCommon::GetCurrentUserId(Constants::UNSPECIFIED_USERID);
4273     std::vector<AbilityInfo> abilityInfos;
4274     int32_t flags = static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL_URI);
4275     ErrCode res = bundleMgrProxy_->QueryAbilityInfosV9(want, flags, userId, abilityInfos);
4276     if (res != OHOS::ERR_OK) {
4277         return res;
4278     }
4279     for (auto &ability: abilityInfos) {
4280         msg += "Ability start\n";
4281         for (auto &uri: ability.skillUri) {
4282             msg += "{\n";
4283             msg += "    scheme: " + uri.scheme + "\n";
4284             msg += "    host: " + uri.host + "\n";
4285             msg += "    port: " + uri.port + "\n";
4286             msg += "    path: " + uri.path + "\n";
4287             msg += "    pathStartWith: " + uri.pathStartWith + "\n";
4288             msg += "    pathRegex: " + uri.pathRegex + "\n";
4289             msg += "    type: " + uri.type + "\n";
4290             msg += "    utd: " + uri.utd + "\n";
4291             msg += "    maxFileSupported: " + std::to_string(uri.maxFileSupported) + "\n";
4292             msg += "    linkFeature: " + uri.linkFeature + "\n";
4293             msg += "    isMatch: " + std::to_string(uri.isMatch) + "\n";
4294             msg += "}\n";
4295         }
4296         msg += "Ability end\n";
4297     }
4298     return res;
4299 }
4300 
RunAsImplicitQuerySkillUriInfo()4301 ErrCode BundleTestTool::RunAsImplicitQuerySkillUriInfo()
4302 {
4303     APP_LOGI("RunAsGetAbilityInfoWithSkillUriFlag start");
4304     int result = OHOS::ERR_OK;
4305     int counter = 0;
4306     std::string bundleName = "";
4307     std::string action = "";
4308     std::string entity = "";
4309     std::string uri = "";
4310     std::string type = "";
4311     while (true) {
4312         counter++;
4313         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO.c_str(),
4314             LONG_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO, nullptr);
4315         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4316         if (optind < 0 || optind > argc_) {
4317             return OHOS::ERR_INVALID_VALUE;
4318         }
4319         if (option == -1) {
4320             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4321                 resultReceiver_.append(HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO);
4322                 return OHOS::ERR_INVALID_VALUE;
4323             }
4324             break;
4325         }
4326         std::string value = "";
4327         result = CheckImplicitQueryWantOption(option, value);
4328         bundleName = option == 'n' ? value : bundleName;
4329         action = option == 'a' ? value : action;
4330         entity = option == 'e' ? value : entity;
4331         uri = option == 'u' ? value : uri;
4332         type = option == 't' ? value : type;
4333     }
4334     APP_LOGI("bundleName: %{public}s, action: %{public}s, entity: %{public}s, uri: %{public}s, type: %{public}s",
4335         bundleName.c_str(), action.c_str(), entity.c_str(), uri.c_str(), type.c_str());
4336     if (result != OHOS::ERR_OK) {
4337         resultReceiver_.append(HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO);
4338     } else {
4339         std::string msg;
4340         result = ImplicitQuerySkillUriInfo(bundleName, action, entity, uri, type, msg);
4341         if (result != OHOS::ERR_OK) {
4342             resultReceiver_.append(STRING_IMPLICIT_QUERY_SKILL_URI_INFO_NG);
4343         } else {
4344             resultReceiver_.append(msg);
4345         }
4346         resultReceiver_.append("\n");
4347     }
4348     return result;
4349 }
4350 
RunAsQueryAbilityInfoByContinueType()4351 ErrCode BundleTestTool::RunAsQueryAbilityInfoByContinueType()
4352 {
4353     APP_LOGI("RunAsQueryAbilityInfoByContinueType start");
4354     int result = OHOS::ERR_OK;
4355     int counter = 0;
4356     std::string commandName = "queryAbilityInfoByContinueType";
4357     std::string name = "";
4358     std::string bundleName = "";
4359     std::string continueType = "";
4360     int userId = 100;
4361     while (true) {
4362         counter++;
4363         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE.c_str(),
4364             LONG_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE, nullptr);
4365         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4366         if (optind < 0 || optind > argc_) {
4367             return OHOS::ERR_INVALID_VALUE;
4368         }
4369         if (option == -1) {
4370             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4371                 resultReceiver_.append(HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE);
4372                 return OHOS::ERR_INVALID_VALUE;
4373             }
4374             break;
4375         }
4376         int temp = 0;
4377         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4378             ? OHOS::ERR_INVALID_VALUE : result;
4379         bundleName = option == 'n' ? name : bundleName;
4380         continueType = option == 'c' ? name : continueType;
4381         userId = option == 'u' ? temp : userId;
4382     }
4383     APP_LOGI("bundleName: %{public}s, continueType: %{public}s, userId: %{public}d",
4384         bundleName.c_str(), continueType.c_str(), userId);
4385     if (result != OHOS::ERR_OK) {
4386         resultReceiver_.append(HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE);
4387     } else {
4388         AbilityInfo abilityInfo;
4389         result = bundleMgrProxy_->QueryAbilityInfoByContinueType(bundleName, continueType, abilityInfo, userId);
4390         if (result != OHOS::ERR_OK) {
4391             resultReceiver_.append(STRING_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE_NG);
4392         } else {
4393             nlohmann::json jsonObject = abilityInfo;
4394             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
4395             resultReceiver_.append(results);
4396         }
4397         resultReceiver_.append("\n");
4398     }
4399     return result;
4400 }
4401 
RunAsGetBundleNameByAppId()4402 ErrCode BundleTestTool::RunAsGetBundleNameByAppId()
4403 {
4404     APP_LOGI("RunAsGetBundleNameByAppId start");
4405     std::string appId;
4406     std::string bundleName;
4407     int32_t counter = 0;
4408     while (true) {
4409         counter++;
4410         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLENAME_BY_APPID.c_str(),
4411             LONG_OPTIONS_GET_BUNDLENAME_BY_APPID, nullptr);
4412         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4413         if (optind < 0 || optind > argc_) {
4414             return OHOS::ERR_INVALID_VALUE;
4415         }
4416         if (option == -1) {
4417             // When scanning the first argument
4418             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4419                 APP_LOGD("bundle_test_tool isBundleInstalled with no option.");
4420                 resultReceiver_.append(HELP_MSG_GET_BUNDLENAME_BY_APPID);
4421                 return OHOS::ERR_INVALID_VALUE;
4422             }
4423             break;
4424         }
4425         switch (option) {
4426             case 'a': {
4427                 appId = optarg;
4428                 break;
4429             }
4430             default: {
4431                 resultReceiver_.append(HELP_MSG_GET_BUNDLENAME_BY_APPID);
4432                 return OHOS::ERR_INVALID_VALUE;
4433             }
4434         }
4435     }
4436     auto result = bundleMgrProxy_->GetBundleNameByAppId(appId, bundleName);
4437     if (result == ERR_OK) {
4438         resultReceiver_.append(STRING_GET_BUNDLENAME_BY_APPID_OK);
4439         resultReceiver_.append(bundleName + "\n");
4440     } else {
4441         resultReceiver_.append(STRING_GET_BUNDLENAME_BY_APPID_NG + "errCode is "+ std::to_string(result) + "\n");
4442     }
4443     APP_LOGI("RunAsGetBundleNameByAppId end");
4444     return result;
4445 }
4446 } // AppExecFwk
4447 } // OHOS