• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "bundle_test_tool.h"
16 
17 #include <chrono>
18 #include <cstdlib>
19 #include <cstring>
20 #include <future>
21 #include <getopt.h>
22 #include <iostream>
23 #include <set>
24 #include <sstream>
25 #include <unistd.h>
26 #include <vector>
27 
28 #include "app_log_wrapper.h"
29 #include "appexecfwk_errors.h"
30 #include "bundle_command_common.h"
31 #include "bundle_death_recipient.h"
32 #include "bundle_mgr_client.h"
33 #include "bundle_mgr_proxy.h"
34 #include "bundle_tool_callback_stub.h"
35 #include "directory_ex.h"
36 #include "parameter.h"
37 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
38 #include "quick_fix_status_callback_host_impl.h"
39 #endif
40 #include "status_receiver_impl.h"
41 #include "string_ex.h"
42 #include "json_util.h"
43 
44 namespace OHOS {
45 namespace AppExecFwk {
46 namespace {
47 // param
48 const int32_t INDEX_OFFSET = 2;
49 // quick fix error code
50 const int32_t ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED = 801;
51 // quick fix error message
52 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR = "error: quick fix internal error.\n";
53 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR = "error: param error.\n";
54 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED = "error: profile parse failed.\n";
55 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME = "error: not same bundle name.\n";
56 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME = "error: not same version code.\n";
57 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME = "error: not same version name.\n";
58 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME =
59     "error: not same patch version code.\n";
60 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME =
61     "error: not same patch version name.\n";
62 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME = "error: not same patch type.\n";
63 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE = "error: unknown quick fix type.\n";
64 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE = "error: patch so incompatible.\n";
65 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME = "error: same moduleName.\n";
66 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST = "error: bundle name is not existed.\n";
67 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST = "error: module name is not existed.\n";
68 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME = "error: signature is not existed.\n";
69 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED = "error: quick fix add hqf failed.\n";
70 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED =
71     "error: quick fix save innerAppQuickFix failed.\n";
72 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR =
73     "error: quick fix version code require greater than original hqf.\n";
74 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE = "error: no this quick fix info in database.\n";
75 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS = "error: wrong quick fix status.\n";
76 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO =
77     "error: cannot obtain the bundleInfo from data mgr.\n";
78 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED = "error: quick fix remove path failed.\n";
79 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED = "error: extract diff files failed.\n";
80 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED = "error: apply diff patch failed.\n";
81 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN = "error: unknown.\n";
82 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED = "feature is not supported.\n";
83 const std::string MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT = "error: quick fix operation time out.\n";
84 const std::string MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED = "error: bundleMgr service is dead.\n";
85 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE =
86     "error: hotreload not support release bundle.\n";
87 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED = "error: patch type already existed.\n";
88 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED =
89     "error: hotreload type already existed.\n";
90 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO =
91     "error: no patch info in bundleInfo.\n";
92 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED = "error: quick fix move hqf file failed.\n";
93 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED = "error: quick fix create path failed.\n";
94 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB =
95     "error: old patch or hot reload in db.\n";
96 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SEND_REQUEST_FAILED = "error: send request failed.\n";
97 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REAL_PATH_FAILED = "error: obtain realpath failed.\n";
98 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATH = "error: input invalid path.\n";
99 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OPEN_SOURCE_FILE_FAILED = "error: open source file failed.\n";
100 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_FD_FAILED = "error: create file descriptor failed.\n";
101 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_TARGET_DIR = "error: invalid designated target dir\n";
102 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_TARGET_DIR_FAILED = "error: create target dir failed.\n";
103 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PERMISSION_DENIED = "error: quick fix permission denied.\n";
104 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_WRITE_FILE_FAILED = "error: write file to target dir failed.\n";
105 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM =
106     "error: invalid param for setting debug mode.\n";
107 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR =
108     "error: internal error for setting debug mode.\n";
109 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR = "error: parcel error for setting debug mode.\n";
110 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR = "error: send request error.\n";
111 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED = "error: uid check failed.\n";
112 
113 static const std::string TOOL_NAME = "bundle_test_tool";
114 static const std::string HELP_MSG = "usage: bundle_test_tool <command> <options>\n"
115                              "These are common bundle_test_tool commands list:\n"
116                              "  help         list available commands\n"
117                              "  setrm        set module isRemovable by given bundle name and module name\n"
118                              "  getrm        obtain the value of isRemovable by given bundle name and module name\n"
119                              "  installSandbox      indicates install sandbox\n"
120                              "  uninstallSandbox    indicates uninstall sandbox\n"
121                              "  dumpSandbox         indicates dump sandbox info\n"
122                              "  getStr      obtain the value of label by given bundle name, module name and label id\n"
123                              "  getIcon     obtain the value of icon by given bundle name, module name,\n"
124                              "              density and icon id\n"
125                              "  addAppInstallRule     obtain the value of install controlRule by given some app id\n"
126                              "                        control rule type, user id and euid\n"
127                              "  getAppInstallRule     obtain the value of install controlRule by given some app id\n"
128                              "                        rule type, user id and euid\n"
129                              "  deleteAppInstallRule  obtain the value of install controlRule by given some app id\n"
130                              "                        user id and euid\n"
131                              "  cleanAppInstallRule   obtain the value of install controlRule by given rule type\n"
132                              "                        user id and euid\n"
133                              "  addAppRunningRule     obtain the value of app running control rule\n"
134                              "                        by given controlRule user id and euidn"
135                              "  deleteAppRunningRule  obtain the value of app running control rule\n"
136                              "                        by given controlRule user id and euid\n"
137                              "  cleanAppRunningRule   obtain the value of app running control\n"
138                              "                        rule by given user id and euid\n"
139                              "  getAppRunningControlRule  obtain the value of app running control rule\n"
140                              "                            by given user id and euid and some app id\n"
141                              "  getAppRunningControlRuleResult     obtain the value of app running control rule\n"
142                              "                      by given bundleName user id, euid and controlRuleResult\n"
143                              "  deployQuickFix      deploy a quick fix patch of an already installed bundle\n"
144                              "  switchQuickFix      switch a quick fix patch of an already installed bundle\n"
145                              "  deleteQuickFix      delete a quick fix patch of an already installed bundle\n"
146                              "  setDebugMode        enable signature debug mode\n"
147                              "  getBundleStats        get bundle stats\n";
148 
149 const std::string HELP_MSG_GET_REMOVABLE =
150     "usage: bundle_test_tool getrm <options>\n"
151     "eg:bundle_test_tool getrm -m <module-name> -n <bundle-name> \n"
152     "options list:\n"
153     "  -h, --help                             list available commands\n"
154     "  -n, --bundle-name  <bundle-name>       get isRemovable by moduleNmae and bundleName\n"
155     "  -m, --module-name <module-name>        get isRemovable by moduleNmae and bundleName\n";
156 
157 const std::string HELP_MSG_NO_REMOVABLE_OPTION =
158     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
159     "and a module name with '-m' or '--module-name' \n";
160 
161 const std::string HELP_MSG_SET =
162     "usage: bundle_test_tool setrm <options>\n"
163     "eg:bundle_test_tool setrm -m <module-name> -n <bundle-name> -i 1\n"
164     "options list:\n"
165     "  -h, --help                               list available commands\n"
166     "  -n, --bundle-name  <bundle-name>         set isRemovable by moduleNmae and bundleName\n"
167     "  -i, --is-removable <is-removable>        set isRemovable  0 or 1\n"
168     "  -m, --module-name <module-name>          set isRemovable by moduleNmae and bundleName\n";
169 
170 const std::string HELP_MSG_INSTALL_SANDBOX =
171     "usage: bundle_test_tool installSandbox <options>\n"
172     "options list:\n"
173     "  -h, --help                             list available commands\n"
174     "  -u, --user-id <user-id>                specify a user id\n"
175     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n"
176     "  -d, --dlp-type <dlp-type>              specify type of the sandbox application\n";
177 
178 const std::string HELP_MSG_UNINSTALL_SANDBOX =
179     "usage: bundle_test_tool uninstallSandbox <options>\n"
180     "options list:\n"
181     "  -h, --help                             list available commands\n"
182     "  -u, --user-id <user-id>                specify a user id\n"
183     "  -a, --app-index <app-index>            specify a app index\n"
184     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
185 
186 const std::string HELP_MSG_DUMP_SANDBOX =
187     "usage: bundle_test_tool dumpSandbox <options>\n"
188     "options list:\n"
189     "  -h, --help                             list available commands\n"
190     "  -u, --user-id <user-id>                specify a user id\n"
191     "  -a, --app-index <app-index>            specify a app index\n"
192     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
193 
194 const std::string HELP_MSG_GET_STRING =
195     "usage: bundle_test_tool getStr <options>\n"
196     "eg:bundle_test_tool getStr -m <module-name> -n <bundle-name> -u <user-id> -i --id <id> \n"
197     "options list:\n"
198     "  -h, --help                             list available commands\n"
199     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
200     "  -m, --module-name <module-name>        specify module name of the application\n"
201     "  -u, --user-id <user-id>                specify a user id\n"
202     "  -i, --id <id>                          specify a label id of the application\n";
203 
204 const std::string HELP_MSG_GET_ICON =
205     "usage: bundle_test_tool getIcon <options>\n"
206     "eg:bundle_test_tool getIcon -m <module-name> -n <bundle-name> -u <user-id> -d --density <density> -i --id <id> \n"
207     "options list:\n"
208     "  -h, --help                             list available commands\n"
209     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
210     "  -m, --module-name <module-name>        specify module name of the application\n"
211     "  -u, --user-id <user-id>                specify a user id\n"
212     "  -d, --density <density>                specify a density\n"
213     "  -i, --id <id>                          specify a icon id of the application\n";
214 
215 const std::string HELP_MSG_NO_GETSTRING_OPTION =
216     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
217     "and a module name with '-m' or '--module-name' \n"
218     "and a userid with '-u' or '--user-id' \n"
219     "and a labelid with '-i' or '--id' \n";
220 
221 const std::string HELP_MSG_NO_GETICON_OPTION =
222     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
223     "and a module name with '-m' or '--module-name' \n"
224     "and a userid with '-u' or '--user-id' \n"
225     "and a density with '-d' or '--density' \n"
226     "and a iconid with '-i' or '--id' \n";
227 
228 const std::string HELP_MSG_ADD_INSTALL_RULE =
229     "usage: bundle_test_tool <options>\n"
230     "eg:bundle_test_tool addAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
231     "options list:\n"
232     "  -h, --help                             list available commands\n"
233     "  -a, --app-id <app-id>                  specify app id of the application\n"
234     "  -e, --euid <eu-id>                     default euid value is 537\n"
235     "  -t, --control-rule-type                specify control type of the application\n"
236     "  -u, --user-id <user-id>                specify a user id\n";
237 
238 const std::string HELP_MSG_GET_INSTALL_RULE =
239     "usage: bundle_test_tool <options>\n"
240     "eg:bundle_test_tool getAppInstallRule -t <control-rule-type> -u <user-id> \n"
241     "options list:\n"
242     "  -h, --help                             list available commands\n"
243     "  -e, --euid <eu-id>                     default euid value is 537\n"
244     "  -t, --control-rule-type                specify control type of the application\n"
245     "  -u, --user-id <user-id>                specify a user id\n";
246 
247 const std::string HELP_MSG_DELETE_INSTALL_RULE =
248     "usage: bundle_test_tool <options>\n"
249     "eg:bundle_test_tool deleteAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
250     "options list:\n"
251     "  -h, --help                             list available commands\n"
252     "  -e, --euid <eu-id>                     default euid value is 537\n"
253     "  -a, --app-id <app-id>                  specify app id of the application\n"
254     "  -t, --control-rule-type                specify control type of the application\n"
255     "  -u, --user-id <user-id>                specify a user id\n";
256 
257 const std::string HELP_MSG_CLEAN_INSTALL_RULE =
258     "usage: bundle_test_tool <options>\n"
259     "eg:bundle_test_tool cleanAppInstallRule -t <control-rule-type> -u <user-id> \n"
260     "options list:\n"
261     "  -h, --help                             list available commands\n"
262     "  -e, --euid <eu-id>                     default euid value is 537\n"
263     "  -t, --control-rule-type                specify control type of the application\n"
264     "  -u, --user-id <user-id>                specify a user id\n";
265 
266 const std::string HELP_MSG_ADD_APP_RUNNING_RULE =
267     "usage: bundle_test_tool <options>\n"
268     "eg:bundle_test_tool addAppRunningRule -c <control-rule> -u <user-id> \n"
269     "options list:\n"
270     "  -h, --help                             list available commands\n"
271     "  -e, --euid <eu-id>                     default euid value is 537\n"
272     "  -c, --control-rule                     specify control rule of the application\n"
273     "  -u, --user-id <user-id>                specify a user id\n";
274 
275 const std::string HELP_MSG_DELETE_APP_RUNNING_RULE =
276     "usage: bundle_test_tool <options>\n"
277     "eg:bundle_test_tool deleteAppRunningRule -c <control-rule> -u <user-id> \n"
278     "options list:\n"
279     "  -h, --help                             list available commands\n"
280     "  -e, --euid <eu-id>                     default euid value is 537\n"
281     "  -c, --control-rule                     specify control rule of the application\n"
282     "  -u, --user-id <user-id>                specify a user id\n";
283 
284 const std::string HELP_MSG_CLEAN_APP_RUNNING_RULE =
285     "usage: bundle_test_tool <options>\n"
286     "eg:bundle_test_tool cleanAppRunningRule -u <user-id> \n"
287     "options list:\n"
288     "  -h, --help                             list available commands\n"
289     "  -e, --euid <eu-id>                     default euid value is 537\n"
290     "  -u, --user-id <user-id>                specify a user id\n";
291 
292 const std::string HELP_MSG_GET_APP_RUNNING_RULE =
293     "usage: bundle_test_tool <options>\n"
294     "eg:bundle_test_tool getAppRunningControlRule -u <user-id> \n"
295     "options list:\n"
296     "  -h, --help                             list available commands\n"
297     "  -e, --euid <eu-id>                     default euid value is 537\n"
298     "  -u, --user-id <user-id>                specify a user id\n";
299 
300 const std::string HELP_MSG_GET_APP_RUNNING_RESULT_RULE =
301     "usage: bundle_test_tool <options>\n"
302     "eg:bundle_test_tool getAppRunningControlRuleResult -n <bundle-name> \n"
303     "options list:\n"
304     "  -h, --help                             list available commands\n"
305     "  -e, --euid <eu-id>                     default euid value is 537\n"
306     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
307     "  -u, --user-id <user-id>                specify a user id\n";
308 
309 const std::string HELP_MSG_NO_ADD_INSTALL_RULE_OPTION =
310     "error: you must specify a app id with '-a' or '--app-id' \n"
311     "and a control type with '-t' or '--control-rule-type' \n"
312     "and a userid with '-u' or '--user-id' \n";
313 
314 const std::string HELP_MSG_NO_GET_INSTALL_RULE_OPTION =
315     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
316     "and a userid with '-u' or '--user-id' \n";
317 
318 const std::string HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION =
319     "error: you must specify a control type with '-a' or '--app-id' \n"
320     "and a userid with '-u' or '--user-id' \n";
321 
322 const std::string HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION =
323     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
324     "and a userid with '-u' or '--user-id' \n";
325 
326 const std::string HELP_MSG_NO_APP_RUNNING_RULE_OPTION =
327     "error: you must specify a app running type with '-c' or '--control-rule' \n"
328     "and a userid with '-u' or '--user-id' \n";
329 
330 const std::string HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION =
331     "error: you must specify a app running type with a userid '-u' or '--user-id \n";
332 
333 const std::string HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION =
334     "error: you must specify a app running type with '-a' or '--app-id' \n"
335     "and a userid with '-u' or '--user-id' \n";
336 
337 const std::string HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION =
338     "error: you must specify a app running type with '-n' or '--bundle-name' \n"
339     "and a userid with '-u' or '--user-id' \n";
340 
341 const std::string HELP_MSG_DEPLOY_QUICK_FIX =
342     "usage: bundle_test_tool deploy quick fix <options>\n"
343     "eg:bundle_test_tool deployQuickFix -p <quickFixPath> \n"
344     "options list:\n"
345     "  -h, --help                             list available commands\n"
346     "  -p, --patch-path  <patch-path>         specify patch path of the patch\n";
347 
348 const std::string HELP_MSG_SWITCH_QUICK_FIX =
349     "usage: bundle_test_tool switch quick fix <options>\n"
350     "eg:bundle_test_tool switchQuickFix -n <bundle-name> \n"
351     "options list:\n"
352     "  -h, --help                             list available commands\n"
353     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n"
354     "  -e, --enbale  <enable>                 enable a deployed patch of disable an under using patch,\n"
355     "                                         1 represents enable and 0 represents disable\n";
356 
357 const std::string HELP_MSG_DELETE_QUICK_FIX =
358     "usage: bundle_test_tool delete quick fix <options>\n"
359     "eg:bundle_test_tool deleteQuickFix -n <bundle-name> \n"
360     "options list:\n"
361     "  -h, --help                             list available commands\n"
362     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n";
363 
364 const std::string HELP_MSG_SET_DEBUG_MODE =
365     "usage: bundle_test_tool setDebugMode <options>\n"
366     "eg:bundle_test_tool setDebugMode -e <0/1>\n"
367     "options list:\n"
368     "  -h, --help                             list available commands\n"
369     "  -e, --enable  <enable>                 enable signature debug mode, 1 represents enable debug mode and 0\n"
370     "                                         represents disable debug mode\n";
371 
372 const std::string HELP_MSG_GET_BUNDLE_STATS =
373     "usage: bundle_test_tool getBundleStats <options>\n"
374     "eg:bundle_test_tool getBundleStats -n <bundle-name>\n"
375     "options list:\n"
376     "  -h, --help                             list available commands\n"
377     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
378     "  -u, --user-id <user-id>                specify a user id\n";
379 
380 const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION =
381     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
382 
383 const std::string STRING_SET_REMOVABLE_OK = "set removable is ok \n";
384 const std::string STRING_SET_REMOVABLE_NG = "error: failed to set removable \n";
385 const std::string STRING_GET_REMOVABLE_OK = "get removable is ok \n";
386 const std::string STRING_GET_REMOVABLE_NG = "error: failed to get removable \n";
387 const std::string STRING_REQUIRE_CORRECT_VALUE =
388     "error: option requires a correct value or note that\n"
389     "the difference in expressions between short option and long option. \n";
390 
391 const std::string STRING_INSTALL_SANDBOX_SUCCESSFULLY = "install sandbox app successfully \n";
392 const std::string STRING_INSTALL_SANDBOX_FAILED = "install sandbox app failed \n";
393 
394 const std::string STRING_UNINSTALL_SANDBOX_SUCCESSFULLY = "uninstall sandbox app successfully\n";
395 const std::string STRING_UNINSTALL_SANDBOX_FAILED = "uninstall sandbox app failed\n";
396 
397 const std::string STRING_DUMP_SANDBOX_FAILED = "dump sandbox app info failed\n";
398 
399 const std::string STRING_GET_STRING_NG = "error: failed to get label \n";
400 
401 const std::string STRING_GET_ICON_NG = "error: failed to get icon \n";
402 
403 const std::string STRING_ADD_RULE_NG = "error: failed to add rule \n";
404 const std::string STRING_GET_RULE_NG = "error: failed to get rule \n";
405 const std::string STRING_DELETE_RULE_NG = "error: failed to delete rule \n";
406 
407 const std::string STRING_DEPLOY_QUICK_FIX_OK = "deploy quick fix successfully\n";
408 const std::string STRING_DEPLOY_QUICK_FIX_NG = "deploy quick fix failed\n";
409 const std::string HELP_MSG_NO_QUICK_FIX_PATH_OPTION = "need a quick fix patch path\n";
410 const std::string STRING_SWITCH_QUICK_FIX_OK = "switch quick fix successfully\n";
411 const std::string STRING_SWITCH_QUICK_FIX_NG = "switch quick fix failed\n";
412 const std::string STRING_DELETE_QUICK_FIX_OK = "delete quick fix successfully\n";
413 const std::string STRING_DELETE_QUICK_FIX_NG = "delete quick fix failed\n";
414 
415 const std::string STRING_SET_DEBUG_MODE_OK = "set debug mode successfully\n";
416 const std::string STRING_SET_DEBUG_MODE_NG = "set debug mode failed\n";
417 
418 const std::string STRING_GET_BUNDLE_STATS_OK = "get bundle stats successfully\n";
419 const std::string STRING_GET_BUNDLE_STATS_NG = "get bundle stats failed\n";
420 
421 const std::string GET_BUNDLE_STATS_ARRAY[] = {
422     "app data size: ",
423     "user data size: ",
424     "distributed data size: ",
425     "database size: ",
426     "cache size: "
427 };
428 
429 const std::string GET_RM = "getrm";
430 const std::string SET_RM = "setrm";
431 const std::string INSTALL_SANDBOX = "installSandbox";
432 const std::string UNINSTALL_SANDBOX = "uninstallSandbox";
433 const std::string DUMP_SANDBOX = "dumpSandbox";
434 
435 const std::string SHORT_OPTIONS = "hn:m:a:d:u:i:";
436 const struct option LONG_OPTIONS[] = {
437     {"help", no_argument, nullptr, 'h'},
438     {"bundle-name", required_argument, nullptr, 'n'},
439     {"module-name", required_argument, nullptr, 'm'},
440     {"ability-name", required_argument, nullptr, 'a'},
441     {"device-id", required_argument, nullptr, 'd'},
442     {"user-id", required_argument, nullptr, 'u'},
443     {"is-removable", required_argument, nullptr, 'i'},
444     {nullptr, 0, nullptr, 0},
445 };
446 
447 const std::string SHORT_OPTIONS_SANDBOX = "hn:d:u:a:";
448 const struct option LONG_OPTIONS_SANDBOX[] = {
449     {"help", no_argument, nullptr, 'h'},
450     {"bundle-name", required_argument, nullptr, 'n'},
451     {"user-id", required_argument, nullptr, 'u'},
452     {"dlp-type", required_argument, nullptr, 'd'},
453     {"app-index", required_argument, nullptr, 'a'},
454     {nullptr, 0, nullptr, 0},
455 };
456 
457 const std::string SHORT_OPTIONS_GET = "hn:m:u:i:d:";
458 const struct option LONG_OPTIONS_GET[] = {
459     {"help", no_argument, nullptr, 'h'},
460     {"bundle-name", required_argument, nullptr, 'n'},
461     {"module-name", required_argument, nullptr, 'm'},
462     {"user-id", required_argument, nullptr, 'u'},
463     {"id", required_argument, nullptr, 'i'},
464     {"density", required_argument, nullptr, 'd'},
465     {nullptr, 0, nullptr, 0},
466 };
467 
468 const std::string SHORT_OPTIONS_RULE = "ha:c:n:e:r:t:u:";
469 const struct option LONG_OPTIONS_RULE[] = {
470     {"help", no_argument, nullptr, 'h'},
471     {"app-id", required_argument, nullptr, 'a'},
472     {"control-rule", required_argument, nullptr, 'c'},
473     {"bundle-name", required_argument, nullptr, 'n'},
474     {"bundle-name", required_argument, nullptr, 'n'},
475     {"euid", required_argument, nullptr, 'e'},
476     {"control-rule-type", required_argument, nullptr, 't'},
477     {"user-id", required_argument, nullptr, 'u'},
478     {nullptr, 0, nullptr, 0},
479 };
480 
481 const std::string SHORT_OPTIONS_QUICK_FIX = "hp:n:e:";
482 const struct option LONG_OPTIONS_QUICK_FIX[] = {
483     {"help", no_argument, nullptr, 'h'},
484     {"patch-path", required_argument, nullptr, 'p'},
485     {"bundle-name", required_argument, nullptr, 'n'},
486     {"enable", required_argument, nullptr, 'e'},
487     {nullptr, 0, nullptr, 0},
488 };
489 
490 const std::string SHORT_OPTIONS_DEBUG_MODE = "he:";
491 const struct option LONG_OPTIONS_DEBUG_MODE[] = {
492     {"help", no_argument, nullptr, 'h'},
493     {"enable", required_argument, nullptr, 'e'},
494     {nullptr, 0, nullptr, 0},
495 };
496 
497 const std::string SHORT_OPTIONS_GET_BUNDLE_STATS = "hn:u:";
498 const struct option LONG_OPTIONS_GET_BUNDLE_STATS[] = {
499     {"help", no_argument, nullptr, 'h'},
500     {"bundle-name", required_argument, nullptr, 'n'},
501     {"user-id", required_argument, nullptr, 'u'},
502     {nullptr, 0, nullptr, 0},
503 };
504 }  // namespace
505 
BundleTestTool(int argc,char * argv[])506 BundleTestTool::BundleTestTool(int argc, char *argv[]) : ShellCommand(argc, argv, TOOL_NAME)
507 {}
508 
~BundleTestTool()509 BundleTestTool::~BundleTestTool()
510 {}
511 
CreateCommandMap()512 ErrCode BundleTestTool::CreateCommandMap()
513 {
514     commandMap_ = {
515         {"help", std::bind(&BundleTestTool::RunAsHelpCommand, this)},
516         {"check", std::bind(&BundleTestTool::RunAsCheckCommand, this)},
517         {"setrm", std::bind(&BundleTestTool::RunAsSetRemovableCommand, this)},
518         {"getrm", std::bind(&BundleTestTool::RunAsGetRemovableCommand, this)},
519         {"installSandbox", std::bind(&BundleTestTool::RunAsInstallSandboxCommand, this)},
520         {"uninstallSandbox", std::bind(&BundleTestTool::RunAsUninstallSandboxCommand, this)},
521         {"dumpSandbox", std::bind(&BundleTestTool::RunAsDumpSandboxCommand, this)},
522         {"getStr", std::bind(&BundleTestTool::RunAsGetStringCommand, this)},
523         {"getIcon", std::bind(&BundleTestTool::RunAsGetIconCommand, this)},
524         {"addAppInstallRule", std::bind(&BundleTestTool::RunAsAddInstallRuleCommand, this)},
525         {"getAppInstallRule", std::bind(&BundleTestTool::RunAsGetInstallRuleCommand, this)},
526         {"deleteAppInstallRule", std::bind(&BundleTestTool::RunAsDeleteInstallRuleCommand, this)},
527         {"cleanAppInstallRule", std::bind(&BundleTestTool::RunAsCleanInstallRuleCommand, this)},
528         {"addAppRunningRule", std::bind(&BundleTestTool::RunAsAddAppRunningRuleCommand, this)},
529         {"deleteAppRunningRule", std::bind(&BundleTestTool::RunAsDeleteAppRunningRuleCommand, this)},
530         {"cleanAppRunningRule", std::bind(&BundleTestTool::RunAsCleanAppRunningRuleCommand, this)},
531         {"getAppRunningControlRule", std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleCommand, this)},
532         {"getAppRunningControlRuleResult",
533             std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleResultCommand, this)},
534         {"deployQuickFix", std::bind(&BundleTestTool::RunAsDeployQuickFix, this)},
535         {"switchQuickFix", std::bind(&BundleTestTool::RunAsSwitchQuickFix, this)},
536         {"deleteQuickFix", std::bind(&BundleTestTool::RunAsDeleteQuickFix, this)},
537         {"setDebugMode", std::bind(&BundleTestTool::RunAsSetDebugMode, this)},
538         {"getBundleStats", std::bind(&BundleTestTool::RunAsGetBundleStats, this)}
539     };
540 
541     return OHOS::ERR_OK;
542 }
543 
CreateMessageMap()544 ErrCode BundleTestTool::CreateMessageMap()
545 {
546     messageMap_ = BundleCommandCommon::bundleMessageMap_;
547 
548     return OHOS::ERR_OK;
549 }
550 
Init()551 ErrCode BundleTestTool::Init()
552 {
553     APP_LOGI("BundleTestTool Init()");
554     ErrCode result = OHOS::ERR_OK;
555     if (bundleMgrProxy_ == nullptr) {
556         bundleMgrProxy_ = BundleCommandCommon::GetBundleMgrProxy();
557         if (bundleMgrProxy_ != nullptr) {
558             if (bundleInstallerProxy_ == nullptr) {
559                 bundleInstallerProxy_ = bundleMgrProxy_->GetBundleInstaller();
560             }
561         }
562     }
563 
564     if ((bundleMgrProxy_ == nullptr) || (bundleInstallerProxy_ == nullptr) ||
565         (bundleInstallerProxy_->AsObject() == nullptr)) {
566         result = OHOS::ERR_INVALID_VALUE;
567     }
568 
569     return result;
570 }
571 
CreateQuickFixMsgMap(std::unordered_map<int32_t,std::string> & quickFixMsgMap)572 void BundleTestTool::CreateQuickFixMsgMap(std::unordered_map<int32_t, std::string> &quickFixMsgMap)
573 {
574     quickFixMsgMap = {
575         { ERR_OK, Constants::EMPTY_STRING },
576         { ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR },
577         { ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR },
578         { ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED },
579         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME },
580         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME },
581         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME },
582         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME,
583             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME },
584         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME,
585             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME },
586         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME },
587         { ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE },
588         { ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE },
589         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST },
590         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST },
591         { ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME,
592             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME },
593         { ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED,
594             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED },
595         { ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED,
596             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED },
597         { ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED },
598         { ERR_APPEXECFWK_OPERATION_TIME_OUT, MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT },
599         { ERR_APPEXECFWK_FAILED_SERVICE_DIED, MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED },
600         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE,
601             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE },
602         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED },
603         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED,
604             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED },
605         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME },
606         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO,
607             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO },
608         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM },
609         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR },
610         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR },
611         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR,
612             MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR },
613         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED },
614         { ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED },
615         { ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED,
616             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED },
617         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR },
618         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE },
619         { ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS },
620         { ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO,
621             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO },
622         { ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED,
623             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED },
624         { ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED,
625             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED },
626         { ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED,
627             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED },
628         { ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB,
629             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB }
630     };
631 }
632 
RunAsHelpCommand()633 ErrCode BundleTestTool::RunAsHelpCommand()
634 {
635     resultReceiver_.append(HELP_MSG);
636 
637     return OHOS::ERR_OK;
638 }
639 
CheckOperation(int userId,std::string deviceId,std::string bundleName,std::string moduleName,std::string abilityName)640 ErrCode BundleTestTool::CheckOperation(int userId, std::string deviceId, std::string bundleName,
641     std::string moduleName, std::string abilityName)
642 {
643     std::unique_lock<std::mutex> lock(mutex_);
644     sptr<BundleToolCallbackStub> bundleToolCallbackStub =
645         new(std::nothrow) BundleToolCallbackStub(cv_, mutex_, dataReady_);
646     if (bundleToolCallbackStub == nullptr) {
647         APP_LOGE("bundleToolCallbackStub is null");
648         return OHOS::ERR_INVALID_VALUE;
649     }
650     APP_LOGI("CheckAbilityEnableInstall param: userId:%{public}d, bundleName:%{public}s, moduleName:%{public}s," \
651         "abilityName:%{public}s", userId, bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
652     AAFwk::Want want;
653     want.SetElementName(deviceId, bundleName, abilityName, moduleName);
654     bool ret = bundleMgrProxy_->CheckAbilityEnableInstall(want, 1, userId, bundleToolCallbackStub);
655     if (!ret) {
656         APP_LOGE("CheckAbilityEnableInstall failed");
657         return OHOS::ERR_OK;
658     }
659     APP_LOGI("CheckAbilityEnableInstall wait");
660     cv_.wait(lock, [this] { return dataReady_; });
661     dataReady_ = false;
662     return OHOS::ERR_OK;
663 }
664 
RunAsCheckCommand()665 ErrCode BundleTestTool::RunAsCheckCommand()
666 {
667     int counter = 0;
668     int userId = 100;
669     std::string deviceId = "";
670     std::string bundleName = "";
671     std::string moduleName = "";
672     std::string abilityName = "";
673     while (true) {
674         counter++;
675         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
676         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
677         if (optind < 0 || optind > argc_) {
678             return OHOS::ERR_INVALID_VALUE;
679         }
680         if (option == -1) {
681             // When scanning the first argument
682             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
683                 // 'CheckAbilityEnableInstall' with no option: CheckAbilityEnableInstall
684                 // 'CheckAbilityEnableInstall' with a wrong argument: CheckAbilityEnableInstall
685                 APP_LOGD("'CheckAbilityEnableInstall' with no option.");
686                 return OHOS::ERR_INVALID_VALUE;
687             }
688             break;
689         }
690         switch (option) {
691             case 'n': {
692                 bundleName = optarg;
693                 break;
694             }
695             case 'm': {
696                 moduleName = optarg;
697                 break;
698             }
699             case 'a': {
700                 abilityName = optarg;
701                 break;
702             }
703             case 'd': {
704                 deviceId = optarg;
705                 break;
706             }
707             case 'u': {
708                 userId = std::stoi(optarg);
709                 break;
710             }
711             default: {
712                 return OHOS::ERR_INVALID_VALUE;
713             }
714         }
715     }
716     return CheckOperation(userId, deviceId, bundleName, moduleName, abilityName);
717 }
718 
SetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,int isRemovable) const719 bool BundleTestTool::SetIsRemovableOperation(
720     const std::string &bundleName, const std::string &moduleName, int isRemovable) const
721 {
722     bool enable = true;
723     if (isRemovable == 0) {
724         enable = false;
725     }
726     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s, enable:%{public}d", bundleName.c_str(), moduleName.c_str(),
727         enable);
728     auto ret = bundleMgrProxy_->SetModuleRemovable(bundleName, moduleName, enable);
729     APP_LOGD("SetModuleRemovable end bundleName: %{public}d", ret);
730     if (!ret) {
731         APP_LOGE("SetIsRemovableOperation failed");
732         return false;
733     }
734     return ret;
735 }
736 
GetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,std::string & result) const737 bool BundleTestTool::GetIsRemovableOperation(
738     const std::string &bundleName, const std::string &moduleName, std::string &result) const
739 {
740     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
741     bool isRemovable = false;
742     auto ret = bundleMgrProxy_->IsModuleRemovable(bundleName, moduleName, isRemovable);
743     APP_LOGD("IsModuleRemovable end bundleName: %{public}s, isRemovable:%{public}d", bundleName.c_str(), isRemovable);
744     result.append("isRemovable: " + std::to_string(isRemovable) + "\n");
745     if (ret != ERR_OK) {
746         APP_LOGE("IsModuleRemovable failed, ret: %{public}d", ret);
747         return false;
748     }
749     return true;
750 }
751 
CheckRemovableErrorOption(int option,int counter,const std::string & commandName)752 bool BundleTestTool::CheckRemovableErrorOption(int option, int counter, const std::string &commandName)
753 {
754     if (option == -1) {
755         if (counter == 1) {
756             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
757                 // 'bundle_test_tool setrm/getrm' with no option: bundle_test_tool setrm/getrm
758                 // 'bundle_test_tool setrm/getrm' with a wrong argument: bundle_test_tool setrm/getrm xxx
759                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
760                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
761                 return false;
762             }
763         }
764         return true;
765     } else if (option == '?') {
766         switch (optopt) {
767             case 'i': {
768                 if (commandName == GET_RM) {
769                     std::string unknownOption = "";
770                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
771                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
772                     resultReceiver_.append(unknownOptionMsg);
773                 } else {
774                     APP_LOGD("'bundle_test_tool %{public}s -i' with no argument.", commandName.c_str());
775                     resultReceiver_.append("error: -i option requires a value.\n");
776                 }
777                 break;
778             }
779             case 'm': {
780                 APP_LOGD("'bundle_test_tool %{public}s -m' with no argument.", commandName.c_str());
781                 resultReceiver_.append("error: -m option requires a value.\n");
782                 break;
783             }
784             case 'n': {
785                 APP_LOGD("'bundle_test_tool %{public}s -n' with no argument.", commandName.c_str());
786                 resultReceiver_.append("error: -n option requires a value.\n");
787                 break;
788             }
789             default: {
790                 std::string unknownOption = "";
791                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
792                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
793                 resultReceiver_.append(unknownOptionMsg);
794                 break;
795             }
796         }
797     }
798     return false;
799 }
800 
CheckRemovableCorrectOption(int option,const std::string & commandName,int & isRemovable,std::string & name)801 bool BundleTestTool::CheckRemovableCorrectOption(
802     int option, const std::string &commandName, int &isRemovable, std::string &name)
803 {
804     bool ret = true;
805     switch (option) {
806         case 'h': {
807             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
808             ret = false;
809             break;
810         }
811         case 'n': {
812             name = optarg;
813             APP_LOGD("'bundle_test_tool %{public}s -n %{public}s'", commandName.c_str(), argv_[optind - 1]);
814             break;
815         }
816         case 'i': {
817             if (commandName == GET_RM) {
818                 std::string unknownOption = "";
819                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
820                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
821                 resultReceiver_.append(unknownOptionMsg);
822                 ret = false;
823             } else if (OHOS::StrToInt(optarg, isRemovable)) {
824                 APP_LOGD("'bundle_test_tool %{public}s -i isRemovable:%{public}d, %{public}s'",
825                     commandName.c_str(), isRemovable, argv_[optind - 1]);
826             } else {
827                 APP_LOGE("bundle_test_tool setrm with error %{private}s", optarg);
828                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
829                 ret = false;
830             }
831             break;
832         }
833         case 'm': {
834             name = optarg;
835             APP_LOGD("'bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s'",
836                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
837             break;
838         }
839         default: {
840             std::string unknownOption = "";
841             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
842             APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
843             resultReceiver_.append(unknownOptionMsg);
844             ret = false;
845             break;
846         }
847     }
848     return ret;
849 }
850 
RunAsSetRemovableCommand()851 ErrCode BundleTestTool::RunAsSetRemovableCommand()
852 {
853     int result = OHOS::ERR_OK;
854     int counter = 0;
855     int isRemovable = 0;
856     std::string commandName = SET_RM;
857     std::string name = "";
858     std::string bundleName = "";
859     std::string moduleName = "";
860     APP_LOGD("RunAsSetCommand is start");
861     while (true) {
862         counter++;
863         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
864         if (optind < 0 || optind > argc_) {
865             return OHOS::ERR_INVALID_VALUE;
866         }
867         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d, argv_[optind - 1]:%{public}s", option,
868             optopt, optind, argv_[optind - 1]);
869         if (option == -1 || option == '?') {
870             result = !CheckRemovableErrorOption(option, counter, commandName)? OHOS::ERR_INVALID_VALUE : result;
871             break;
872         }
873         result = !CheckRemovableCorrectOption(option, commandName, isRemovable, name)
874             ? OHOS::ERR_INVALID_VALUE : result;
875         moduleName = option == 'm' ? name : moduleName;
876         bundleName = option == 'n' ? name : bundleName;
877     }
878     if (result == OHOS::ERR_OK) {
879         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
880             APP_LOGD("'bundle_test_tool setrm' with not enough option.");
881             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
882             result = OHOS::ERR_INVALID_VALUE;
883         }
884     }
885     if (result != OHOS::ERR_OK) {
886         resultReceiver_.append(HELP_MSG_SET);
887     } else {
888         bool setResult = false;
889         setResult = SetIsRemovableOperation(bundleName, moduleName, isRemovable);
890         APP_LOGD("'bundle_test_tool setrm' isRemovable is %{public}d", isRemovable);
891         resultReceiver_ = setResult ? STRING_SET_REMOVABLE_OK : STRING_SET_REMOVABLE_NG;
892     }
893     return result;
894 }
895 
RunAsGetRemovableCommand()896 ErrCode BundleTestTool::RunAsGetRemovableCommand()
897 {
898     int result = OHOS::ERR_OK;
899     int counter = 0;
900     std::string commandName = GET_RM;
901     std::string name = "";
902     std::string bundleName = "";
903     std::string moduleName = "";
904     APP_LOGD("RunAsGetRemovableCommand is start");
905     while (true) {
906         counter++;
907         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
908         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
909         if (optind < 0 || optind > argc_) {
910             return OHOS::ERR_INVALID_VALUE;
911         }
912         if (option == -1 || option == '?') {
913             result = !CheckRemovableErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
914             break;
915         }
916         int tempIsRem = 0;
917         result = !CheckRemovableCorrectOption(option, commandName, tempIsRem, name)
918             ? OHOS::ERR_INVALID_VALUE : result;
919         moduleName = option == 'm' ? name : moduleName;
920         bundleName = option == 'n' ? name : bundleName;
921     }
922 
923     if (result == OHOS::ERR_OK) {
924         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
925             APP_LOGD("'bundle_test_tool getrm' with no option.");
926             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
927             result = OHOS::ERR_INVALID_VALUE;
928         }
929     }
930 
931     if (result != OHOS::ERR_OK) {
932         resultReceiver_.append(HELP_MSG_GET_REMOVABLE);
933     } else {
934         std::string results = "";
935         GetIsRemovableOperation(bundleName, moduleName, results);
936         if (results.empty()) {
937             resultReceiver_.append(STRING_GET_REMOVABLE_NG);
938             return result;
939         }
940         resultReceiver_.append(results);
941     }
942     return result;
943 }
944 
CheckSandboxErrorOption(int option,int counter,const std::string & commandName)945 bool BundleTestTool::CheckSandboxErrorOption(int option, int counter, const std::string &commandName)
946 {
947     if (option == -1) {
948         if (counter == 1) {
949             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
950                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
951                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
952                 return false;
953             }
954         }
955         return true;
956     } else if (option == '?') {
957         switch (optopt) {
958             case 'n':
959             case 'u':
960             case 'd':
961             case 'a': {
962                 if ((commandName != INSTALL_SANDBOX && optopt == 'd') ||
963                     (commandName == INSTALL_SANDBOX && optopt == 'a')) {
964                     std::string unknownOption = "";
965                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
966                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
967                     resultReceiver_.append(unknownOptionMsg);
968                     break;
969                 }
970                 APP_LOGD("'bundle_test_tool %{public}s' -%{public}c with no argument.", commandName.c_str(), optopt);
971                 resultReceiver_.append("error: option requires a value.\n");
972                 break;
973             }
974             default: {
975                 std::string unknownOption = "";
976                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
977                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
978                 resultReceiver_.append(unknownOptionMsg);
979                 break;
980             }
981         }
982     }
983     return false;
984 }
985 
CheckSandboxCorrectOption(int option,const std::string & commandName,int & data,std::string & bundleName)986 bool BundleTestTool::CheckSandboxCorrectOption(
987     int option, const std::string &commandName, int &data, std::string &bundleName)
988 {
989     bool ret = true;
990     switch (option) {
991         case 'h': {
992             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
993             ret = false;
994             break;
995         }
996         case 'n': {
997             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
998             bundleName = optarg;
999             break;
1000         }
1001         case 'u':
1002         case 'a':
1003         case 'd': {
1004             if ((commandName != INSTALL_SANDBOX && option == 'd') ||
1005                 (commandName == INSTALL_SANDBOX && option == 'a')) {
1006                 std::string unknownOption = "";
1007                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1008                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1009                 resultReceiver_.append(unknownOptionMsg);
1010                 ret = false;
1011                 break;
1012             }
1013 
1014             APP_LOGD("'bundle_test_tool %{public}s %{public}s %{public}s'", commandName.c_str(),
1015                 argv_[optind - OFFSET_REQUIRED_ARGUMENT], optarg);
1016 
1017             if (!OHOS::StrToInt(optarg, data)) {
1018                 if (option == 'u') {
1019                     APP_LOGE("bundle_test_tool %{public}s with error -u %{private}s", commandName.c_str(), optarg);
1020                 } else if (option == 'a') {
1021                     APP_LOGE("bundle_test_tool %{public}s with error -a %{private}s", commandName.c_str(), optarg);
1022                 } else {
1023                     APP_LOGE("bundle_test_tool %{public}s with error -d %{private}s", commandName.c_str(), optarg);
1024                 }
1025                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1026                 ret = false;
1027             }
1028             break;
1029         }
1030         default: {
1031             ret = false;
1032             break;
1033         }
1034     }
1035     return ret;
1036 }
1037 
InstallSandboxOperation(const std::string & bundleName,const int32_t userId,const int32_t dlpType,int32_t & appIndex) const1038 ErrCode BundleTestTool::InstallSandboxOperation(
1039     const std::string &bundleName, const int32_t userId, const int32_t dlpType, int32_t &appIndex) const
1040 {
1041     APP_LOGD("InstallSandboxOperation of bundleName %{public}s, dipType is %{public}d", bundleName.c_str(), dlpType);
1042     return bundleInstallerProxy_->InstallSandboxApp(bundleName, dlpType, userId, appIndex);
1043 }
1044 
RunAsInstallSandboxCommand()1045 ErrCode BundleTestTool::RunAsInstallSandboxCommand()
1046 {
1047     int result = OHOS::ERR_OK;
1048     int counter = 0;
1049     std::string commandName = INSTALL_SANDBOX;
1050     std::string bundleName = "";
1051     int32_t userId = 100;
1052     int32_t dlpType = 0;
1053     while (true) {
1054         counter++;
1055         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1056         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1057         if (optind < 0 || optind > argc_) {
1058             return OHOS::ERR_INVALID_VALUE;
1059         }
1060         if (option == -1 || option == '?') {
1061             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1062             break;
1063         } else if (option == 'u') {
1064             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1065                 OHOS::ERR_INVALID_VALUE : result;
1066         } else {
1067             result = !CheckSandboxCorrectOption(option, commandName, dlpType, bundleName) ?
1068                 OHOS::ERR_INVALID_VALUE : result;
1069         }
1070     }
1071 
1072     if (result == OHOS::ERR_OK && bundleName == "") {
1073         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1074         result = OHOS::ERR_INVALID_VALUE;
1075     } else {
1076         APP_LOGD("installSandbox app bundleName is %{public}s", bundleName.c_str());
1077     }
1078 
1079     if (result != OHOS::ERR_OK) {
1080         resultReceiver_.append(HELP_MSG_INSTALL_SANDBOX);
1081         return result;
1082     }
1083 
1084     int32_t appIndex = 0;
1085     auto ret = InstallSandboxOperation(bundleName, userId, dlpType, appIndex);
1086     if (ret == OHOS::ERR_OK) {
1087         resultReceiver_.append(STRING_INSTALL_SANDBOX_SUCCESSFULLY);
1088     } else {
1089         resultReceiver_.append(STRING_INSTALL_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1090     }
1091     return result;
1092 }
1093 
UninstallSandboxOperation(const std::string & bundleName,const int32_t appIndex,const int32_t userId) const1094 ErrCode BundleTestTool::UninstallSandboxOperation(const std::string &bundleName,
1095     const int32_t appIndex, const int32_t userId) const
1096 {
1097     APP_LOGD("UninstallSandboxOperation of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1098     return bundleInstallerProxy_->UninstallSandboxApp(bundleName, appIndex, userId);
1099 }
1100 
RunAsUninstallSandboxCommand()1101 ErrCode BundleTestTool::RunAsUninstallSandboxCommand()
1102 {
1103     int result = OHOS::ERR_OK;
1104     int counter = 0;
1105     std::string bundleName = "";
1106     std::string commandName = UNINSTALL_SANDBOX;
1107     int32_t userId = 100;
1108     int32_t appIndex = -1;
1109     while (true) {
1110         counter++;
1111         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1112         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1113         if (optind < 0 || optind > argc_) {
1114             return OHOS::ERR_INVALID_VALUE;
1115         }
1116 
1117         if (option == -1 || option == '?') {
1118             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1119             break;
1120         } else if (option == 'u') {
1121             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1122                 OHOS::ERR_INVALID_VALUE : result;
1123         } else {
1124             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1125                 OHOS::ERR_INVALID_VALUE : result;
1126         }
1127     }
1128 
1129     if (result == OHOS::ERR_OK && bundleName == "") {
1130         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1131         result = OHOS::ERR_INVALID_VALUE;
1132     } else {
1133         APP_LOGD("uninstallSandbox app bundleName is %{private}s", bundleName.c_str());
1134     }
1135 
1136     if (result != OHOS::ERR_OK) {
1137         resultReceiver_.append(HELP_MSG_UNINSTALL_SANDBOX);
1138         return result;
1139     }
1140 
1141     auto ret = UninstallSandboxOperation(bundleName, appIndex, userId);
1142     if (ret == ERR_OK) {
1143         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_SUCCESSFULLY);
1144     } else {
1145         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_FAILED + "errCode is " + std::to_string(ret) + "\n");
1146     }
1147     return result;
1148 }
1149 
DumpSandboxBundleInfo(const std::string & bundleName,const int32_t appIndex,const int32_t userId,std::string & dumpResults)1150 ErrCode BundleTestTool::DumpSandboxBundleInfo(const std::string &bundleName, const int32_t appIndex,
1151     const int32_t userId, std::string &dumpResults)
1152 {
1153     APP_LOGD("DumpSandboxBundleInfo of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1154     BundleInfo bundleInfo;
1155     BundleMgrClient client;
1156     auto dumpRet = client.GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo);
1157     if (dumpRet == ERR_OK) {
1158         nlohmann::json jsonObject = bundleInfo;
1159         dumpResults= jsonObject.dump(Constants::DUMP_INDENT);
1160     }
1161     return dumpRet;
1162 }
1163 
RunAsDumpSandboxCommand()1164 ErrCode BundleTestTool::RunAsDumpSandboxCommand()
1165 {
1166     int result = OHOS::ERR_OK;
1167     int counter = 0;
1168     std::string bundleName = "";
1169     std::string commandName = DUMP_SANDBOX;
1170     int32_t userId = 100;
1171     int32_t appIndex = -1;
1172     while (true) {
1173         counter++;
1174         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1175         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1176         if (optind < 0 || optind > argc_) {
1177             return OHOS::ERR_INVALID_VALUE;
1178         }
1179         if (option == -1 || option == '?') {
1180             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1181             break;
1182         } else if (option == 'u') {
1183             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1184                 OHOS::ERR_INVALID_VALUE : result;
1185         } else {
1186             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1187                 OHOS::ERR_INVALID_VALUE : result;
1188         }
1189     }
1190 
1191     if (result == OHOS::ERR_OK && bundleName == "") {
1192         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1193         result = OHOS::ERR_INVALID_VALUE;
1194     } else {
1195         APP_LOGD("dumpSandbox app bundleName is %{public}s", bundleName.c_str());
1196     }
1197 
1198     if (result != OHOS::ERR_OK) {
1199         resultReceiver_.append(HELP_MSG_DUMP_SANDBOX);
1200         return result;
1201     }
1202 
1203     std::string dumpRes = "";
1204     ErrCode ret = DumpSandboxBundleInfo(bundleName, appIndex, userId, dumpRes);
1205     if (ret == ERR_OK) {
1206         resultReceiver_.append(dumpRes);
1207     } else {
1208         resultReceiver_.append(STRING_DUMP_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1209     }
1210     return result;
1211 }
1212 
StringToInt(std::string optarg,const std::string & commandName,int & temp,bool & result)1213 ErrCode BundleTestTool::StringToInt(
1214     std::string optarg, const std::string &commandName, int &temp, bool &result)
1215 {
1216     try {
1217         temp = std::stoi(optarg);
1218         APP_LOGD("bundle_test_tool %{public}s -u user-id:%{public}d, %{public}s",
1219             commandName.c_str(), temp, argv_[optind - 1]);
1220     } catch (const std::exception& e) {
1221         std::cerr << e.what() << std::endl;
1222         result = false;
1223     }
1224     return OHOS::ERR_OK;
1225 }
1226 
CheckGetStringCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1227 bool BundleTestTool::CheckGetStringCorrectOption(
1228     int option, const std::string &commandName, int &temp, std::string &name)
1229 {
1230     bool ret = true;
1231     switch (option) {
1232         case 'h': {
1233             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1234             ret = false;
1235             break;
1236         }
1237         case 'n': {
1238             name = optarg;
1239             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1240             break;
1241         }
1242         case 'm': {
1243             name = optarg;
1244             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1245                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1246             break;
1247         }
1248         case 'u': {
1249             StringToInt(optarg, commandName, temp, ret);
1250             break;
1251         }
1252         case 'i': {
1253             StringToInt(optarg, commandName, temp, ret);
1254             break;
1255         }
1256         default: {
1257             std::string unknownOption = "";
1258             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1259             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1260             resultReceiver_.append(unknownOptionMsg);
1261             ret = false;
1262             break;
1263         }
1264     }
1265     return ret;
1266 }
1267 
RunAsGetStringCommand()1268 ErrCode BundleTestTool::RunAsGetStringCommand()
1269 {
1270     int result = OHOS::ERR_OK;
1271     int counter = 0;
1272     std::string commandName = "getStr";
1273     std::string name = "";
1274     std::string bundleName = "";
1275     std::string moduleName = "";
1276     int userId = 100;
1277     int labelId = 0;
1278     APP_LOGD("RunAsGetStringCommand is start");
1279     while (true) {
1280         counter++;
1281         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
1282         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1283         if (optind < 0 || optind > argc_) {
1284             return OHOS::ERR_INVALID_VALUE;
1285         }
1286         if (option == -1) {
1287             // When scanning the first argument
1288             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1289                 // 'GetStringById' with no option: GetStringById
1290                 // 'GetStringById' with a wrong argument: GetStringById
1291                 APP_LOGD("bundle_test_tool getStr with no option.");
1292                 resultReceiver_.append(HELP_MSG_NO_GETSTRING_OPTION);
1293                 return OHOS::ERR_INVALID_VALUE;
1294             }
1295             break;
1296         }
1297         int temp = 0;
1298         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
1299             ? OHOS::ERR_INVALID_VALUE : result;
1300         moduleName = option == 'm' ? name : moduleName;
1301         bundleName = option == 'n' ? name : bundleName;
1302         userId = option == 'u' ? temp : userId;
1303         labelId = option == 'i' ? temp : labelId;
1304     }
1305 
1306     if (result != OHOS::ERR_OK) {
1307         resultReceiver_.append(HELP_MSG_GET_STRING);
1308     } else {
1309         std::string results = "";
1310         results = bundleMgrProxy_->GetStringById(bundleName, moduleName, labelId, userId);
1311         if (results.empty()) {
1312             resultReceiver_.append(STRING_GET_STRING_NG);
1313             return result;
1314         }
1315         resultReceiver_.append(results);
1316     }
1317     return result;
1318 }
1319 
CheckGetIconCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1320 bool BundleTestTool::CheckGetIconCorrectOption(
1321     int option, const std::string &commandName, int &temp, std::string &name)
1322 {
1323     bool ret = true;
1324     switch (option) {
1325         case 'h': {
1326             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1327             ret = false;
1328             break;
1329         }
1330         case 'n': {
1331             name = optarg;
1332             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1333             break;
1334         }
1335         case 'm': {
1336             name = optarg;
1337             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1338                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1339             break;
1340         }
1341         case 'u': {
1342             StringToInt(optarg, commandName, temp, ret);
1343             break;
1344         }
1345         case 'i': {
1346             StringToInt(optarg, commandName, temp, ret);
1347             break;
1348         }
1349         case 'd': {
1350             StringToInt(optarg, commandName, temp, ret);
1351             break;
1352         }
1353         default: {
1354             std::string unknownOption = "";
1355             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1356             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1357             resultReceiver_.append(unknownOptionMsg);
1358             ret = false;
1359             break;
1360         }
1361     }
1362     return ret;
1363 }
1364 
RunAsGetIconCommand()1365 ErrCode BundleTestTool::RunAsGetIconCommand()
1366 {
1367     int result = OHOS::ERR_OK;
1368     int counter = 0;
1369     std::string commandName = "getIcon";
1370     std::string name = "";
1371     std::string bundleName = "";
1372     std::string moduleName = "";
1373     int userId = 100;
1374     int iconId = 0;
1375     int density = 0;
1376     APP_LOGD("RunAsGetIconCommand is start");
1377     while (true) {
1378         counter++;
1379         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
1380         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1381         if (optind < 0 || optind > argc_) {
1382             return OHOS::ERR_INVALID_VALUE;
1383         }
1384         if (option == -1) {
1385             // When scanning the first argument
1386             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1387                 // 'GetIconById' with no option: GetStringById
1388                 // 'GetIconById' with a wrong argument: GetStringById
1389                 APP_LOGD("bundle_test_tool getIcon with no option.");
1390                 resultReceiver_.append(HELP_MSG_NO_GETICON_OPTION);
1391                 return OHOS::ERR_INVALID_VALUE;
1392             }
1393             break;
1394         }
1395         int temp = 0;
1396         result = !CheckGetIconCorrectOption(option, commandName, temp, name)
1397             ? OHOS::ERR_INVALID_VALUE : result;
1398         moduleName = option == 'm' ? name : moduleName;
1399         bundleName = option == 'n' ? name : bundleName;
1400         userId = option == 'u' ? temp : userId;
1401         iconId = option == 'i' ? temp : iconId;
1402         density = option == 'd' ? temp : density;
1403     }
1404 
1405     if (result != OHOS::ERR_OK) {
1406         resultReceiver_.append(HELP_MSG_GET_ICON);
1407     } else {
1408         std::string results = "";
1409         results = bundleMgrProxy_->GetIconById(bundleName, moduleName, iconId, density, userId);
1410         if (results.empty()) {
1411             resultReceiver_.append(STRING_GET_ICON_NG);
1412             return result;
1413         }
1414         resultReceiver_.append(results);
1415     }
1416     return result;
1417 }
1418 
CheckAddInstallRuleCorrectOption(int option,const std::string & commandName,std::vector<std::string> & appIds,int & controlRuleType,int & userId,int & euid)1419 ErrCode BundleTestTool::CheckAddInstallRuleCorrectOption(int option, const std::string &commandName,
1420     std::vector<std::string> &appIds, int &controlRuleType, int &userId, int &euid)
1421 {
1422     bool ret = true;
1423     switch (option) {
1424         case 'h': {
1425             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1426             return OHOS::ERR_INVALID_VALUE;
1427         }
1428         case 'a': {
1429             std::string arrayAppId = optarg;
1430             std::stringstream array(arrayAppId);
1431             std::string object;
1432             while (getline(array, object, ',')) {
1433                 appIds.emplace_back(object);
1434             }
1435             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
1436             break;
1437         }
1438         case 'e': {
1439             StringToInt(optarg, commandName, euid, ret);
1440             break;
1441         }
1442         case 't': {
1443             StringToInt(optarg, commandName, controlRuleType, ret);
1444             break;
1445         }
1446         case 'u': {
1447             StringToInt(optarg, commandName, userId, ret);
1448             break;
1449         }
1450         default: {
1451             std::string unknownOption = "";
1452             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1453             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1454             resultReceiver_.append(unknownOptionMsg);
1455             return OHOS::ERR_INVALID_VALUE;
1456         }
1457     }
1458     return OHOS::ERR_OK;
1459 }
1460 
1461 // bundle_test_tool addAppInstallRule -a test1,test2 -t 1 -u 101 -e 537
RunAsAddInstallRuleCommand()1462 ErrCode BundleTestTool::RunAsAddInstallRuleCommand()
1463 {
1464     ErrCode result = OHOS::ERR_OK;
1465     int counter = 0;
1466     std::string commandName = "addAppInstallRule";
1467     std::vector<std::string> appIds;
1468     int euid = 537;
1469     int userId = 100;
1470     int ruleType = 0;
1471     APP_LOGD("RunAsAddInstallRuleCommand is start");
1472     while (true) {
1473         counter++;
1474         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1475         if (optind < 0 || optind > argc_) {
1476             return OHOS::ERR_INVALID_VALUE;
1477         }
1478         if (option == -1) {
1479             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1480                 resultReceiver_.append(HELP_MSG_NO_ADD_INSTALL_RULE_OPTION);
1481                 return OHOS::ERR_INVALID_VALUE;
1482             }
1483             break;
1484         }
1485         result = CheckAddInstallRuleCorrectOption(option, commandName, appIds, ruleType, userId, euid);
1486         if (result != OHOS::ERR_OK) {
1487             resultReceiver_.append(HELP_MSG_ADD_INSTALL_RULE);
1488             return OHOS::ERR_INVALID_VALUE;
1489         }
1490     }
1491     seteuid(euid);
1492     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
1493     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1494     if (!appControlProxy) {
1495         APP_LOGE("fail to get app control proxy.");
1496         return OHOS::ERR_INVALID_VALUE;
1497     }
1498     std::string appIdParam = "";
1499     for (auto param : appIds) {
1500         appIdParam = appIdParam.append(param) + ";";
1501     }
1502     APP_LOGI("appIds: %{public}s, controlRuleType: %{public}d, userId: %{public}d",
1503         appIdParam.c_str(), ruleType, userId);
1504     int32_t res = appControlProxy->AddAppInstallControlRule(appIds, rule, userId);
1505     APP_LOGI("AddAppInstallControlRule return code: %{public}d", res);
1506     if (res != OHOS::ERR_OK) {
1507         resultReceiver_.append(STRING_ADD_RULE_NG);
1508         return res;
1509     }
1510     resultReceiver_.append(std::to_string(res) + "\n");
1511     return result;
1512 }
1513 
CheckGetInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)1514 ErrCode BundleTestTool::CheckGetInstallRuleCorrectOption(int option, const std::string &commandName,
1515     int &controlRuleType, int &userId, int &euid)
1516 {
1517     bool ret = true;
1518     switch (option) {
1519         case 'h': {
1520             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1521             return OHOS::ERR_INVALID_VALUE;
1522         }
1523         case 'e': {
1524             StringToInt(optarg, commandName, euid, ret);
1525             break;
1526         }
1527         case 't': {
1528             StringToInt(optarg, commandName, controlRuleType, ret);
1529             break;
1530         }
1531         case 'u': {
1532             StringToInt(optarg, commandName, userId, ret);
1533             break;
1534         }
1535         default: {
1536             std::string unknownOption = "";
1537             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1538             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1539             resultReceiver_.append(unknownOptionMsg);
1540             return OHOS::ERR_INVALID_VALUE;
1541         }
1542     }
1543     return OHOS::ERR_OK;
1544 }
1545 
1546 // bundle_test_tool getAppInstallRule -t 1 -u 101 -e 537
RunAsGetInstallRuleCommand()1547 ErrCode BundleTestTool::RunAsGetInstallRuleCommand()
1548 {
1549     ErrCode result = OHOS::ERR_OK;
1550     int counter = 0;
1551     std::string commandName = "getAppInstallRule";
1552     int euid = 537;
1553     int userId = 100;
1554     int ruleType = 0;
1555     APP_LOGD("RunAsGetInstallRuleCommand is start");
1556     while (true) {
1557         counter++;
1558         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1559         if (optind < 0 || optind > argc_) {
1560             return OHOS::ERR_INVALID_VALUE;
1561         }
1562         if (option == -1) {
1563             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1564                 resultReceiver_.append(HELP_MSG_NO_GET_INSTALL_RULE_OPTION);
1565                 return OHOS::ERR_INVALID_VALUE;
1566             }
1567             break;
1568         }
1569         result = CheckGetInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
1570         if (result != OHOS::ERR_OK) {
1571             resultReceiver_.append(HELP_MSG_GET_INSTALL_RULE);
1572             return OHOS::ERR_INVALID_VALUE;
1573         }
1574     }
1575     seteuid(euid);
1576     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1577     if (!appControlProxy) {
1578         APP_LOGE("fail to get app control proxy.");
1579         return OHOS::ERR_INVALID_VALUE;
1580     }
1581     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
1582     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
1583     std::vector<std::string> appIds;
1584     int32_t res = appControlProxy->GetAppInstallControlRule(rule, userId, appIds);
1585     APP_LOGI("GetAppInstallControlRule return code: %{public}d", res);
1586     if (res != OHOS::ERR_OK) {
1587         resultReceiver_.append(STRING_GET_RULE_NG);
1588         return res;
1589     }
1590     std::string appIdParam = "";
1591     for (auto param : appIds) {
1592         appIdParam = appIdParam.append(param) + "; ";
1593     }
1594     resultReceiver_.append("appId : " + appIdParam + "\n");
1595     return result;
1596 }
1597 
CheckDeleteInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,std::vector<std::string> & appIds,int & userId,int & euid)1598 ErrCode BundleTestTool::CheckDeleteInstallRuleCorrectOption(int option, const std::string &commandName,
1599     int &controlRuleType, std::vector<std::string> &appIds, int &userId, int &euid)
1600 {
1601     bool ret = true;
1602     switch (option) {
1603         case 'h': {
1604             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1605             return OHOS::ERR_INVALID_VALUE;
1606         }
1607         case 'a': {
1608             std::string arrayAppId = optarg;
1609             std::stringstream array(arrayAppId);
1610             std::string object;
1611             while (getline(array, object, ',')) {
1612                 appIds.emplace_back(object);
1613             }
1614             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
1615             break;
1616         }
1617         case 'e': {
1618             StringToInt(optarg, commandName, euid, ret);
1619             break;
1620         }
1621         case 't': {
1622             StringToInt(optarg, commandName, controlRuleType, ret);
1623             break;
1624         }
1625         case 'u': {
1626             StringToInt(optarg, commandName, userId, ret);
1627             break;
1628         }
1629         default: {
1630             std::string unknownOption = "";
1631             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1632             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1633             resultReceiver_.append(unknownOptionMsg);
1634             return OHOS::ERR_INVALID_VALUE;
1635         }
1636     }
1637     return OHOS::ERR_OK;
1638 }
1639 
1640 // bundle_test_tool deleteAppInstallRule -a test1 -t 1 -u 101 -e 537
RunAsDeleteInstallRuleCommand()1641 ErrCode BundleTestTool::RunAsDeleteInstallRuleCommand()
1642 {
1643     ErrCode result = OHOS::ERR_OK;
1644     int counter = 0;
1645     int euid = 537;
1646     std::string commandName = "deleteAppInstallRule";
1647     std::vector<std::string> appIds;
1648     int ruleType = 0;
1649     int userId = 100;
1650     APP_LOGD("RunAsDeleteInstallRuleCommand is start");
1651     while (true) {
1652         counter++;
1653         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1654         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1655         if (optind < 0 || optind > argc_) {
1656             return OHOS::ERR_INVALID_VALUE;
1657         }
1658         if (option == -1) {
1659             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1660                 resultReceiver_.append(HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION);
1661                 return OHOS::ERR_INVALID_VALUE;
1662             }
1663             break;
1664         }
1665         result = CheckDeleteInstallRuleCorrectOption(option, commandName, ruleType, appIds, userId, euid);
1666         if (result != OHOS::ERR_OK) {
1667             resultReceiver_.append(HELP_MSG_DELETE_INSTALL_RULE);
1668             return OHOS::ERR_INVALID_VALUE;
1669         }
1670     }
1671     seteuid(euid);
1672     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1673     if (!appControlProxy) {
1674         APP_LOGE("fail to get app control proxy.");
1675         return OHOS::ERR_INVALID_VALUE;
1676     }
1677     std::string appIdParam = "";
1678     for (auto param : appIds) {
1679         appIdParam = appIdParam.append(param) + ";";
1680     }
1681     APP_LOGI("appIds: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
1682     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
1683     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, appIds, userId);
1684     APP_LOGI("DeleteAppInstallControlRule return code: %{public}d", res);
1685     if (res != OHOS::ERR_OK) {
1686         resultReceiver_.append(STRING_DELETE_RULE_NG);
1687         return res;
1688     }
1689     resultReceiver_.append(std::to_string(res) + "\n");
1690     return result;
1691 }
1692 
CheckCleanInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)1693 ErrCode BundleTestTool::CheckCleanInstallRuleCorrectOption(
1694     int option, const std::string &commandName, int &controlRuleType, int &userId, int &euid)
1695 {
1696     bool ret = true;
1697     switch (option) {
1698         case 'h': {
1699             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1700             return OHOS::ERR_INVALID_VALUE;
1701         }
1702         case 'e': {
1703             StringToInt(optarg, commandName, euid, ret);
1704             break;
1705         }
1706         case 't': {
1707             StringToInt(optarg, commandName, controlRuleType, ret);
1708             break;
1709         }
1710         case 'u': {
1711             StringToInt(optarg, commandName, userId, ret);
1712             break;
1713         }
1714         default: {
1715             std::string unknownOption = "";
1716             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1717             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1718             resultReceiver_.append(unknownOptionMsg);
1719             return OHOS::ERR_INVALID_VALUE;
1720         }
1721     }
1722     return OHOS::ERR_OK;
1723 }
1724 
1725 // bundle_test_tool cleanAppInstallRule -t 1 -u 101 -e 537
RunAsCleanInstallRuleCommand()1726 ErrCode BundleTestTool::RunAsCleanInstallRuleCommand()
1727 {
1728     ErrCode result = OHOS::ERR_OK;
1729     int counter = 0;
1730     int euid = 537;
1731     std::string commandName = "cleanAppInstallRule";
1732     int userId = 100;
1733     int ruleType = 0;
1734     APP_LOGD("RunAsCleanInstallRuleCommand is start");
1735     while (true) {
1736         counter++;
1737         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1738         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1739         if (optind < 0 || optind > argc_) {
1740             return OHOS::ERR_INVALID_VALUE;
1741         }
1742         if (option == -1) {
1743             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1744                 APP_LOGD("bundle_test_tool getRule with no option.");
1745                 resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
1746                 return OHOS::ERR_INVALID_VALUE;
1747             }
1748             break;
1749         }
1750         result = CheckCleanInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
1751         if (result != OHOS::ERR_OK) {
1752             resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
1753             return OHOS::ERR_INVALID_VALUE;
1754         }
1755     }
1756     seteuid(euid);
1757     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
1758     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1759     if (!appControlProxy) {
1760         APP_LOGE("fail to get app control proxy.");
1761         return OHOS::ERR_INVALID_VALUE;
1762     }
1763     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
1764     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, userId);
1765     APP_LOGI("DeleteAppInstallControlRule clean return code: %{public}d", res);
1766     if (res != OHOS::ERR_OK) {
1767         resultReceiver_.append(STRING_DELETE_RULE_NG);
1768         return res;
1769     }
1770     resultReceiver_.append(std::to_string(res) + "\n");
1771     return result;
1772 }
1773 
CheckAppRunningRuleCorrectOption(int option,const std::string & commandName,std::vector<AppRunningControlRule> & controlRule,int & userId,int & euid)1774 ErrCode BundleTestTool::CheckAppRunningRuleCorrectOption(int option, const std::string &commandName,
1775     std::vector<AppRunningControlRule> &controlRule, int &userId, int &euid)
1776 {
1777     bool ret = true;
1778     switch (option) {
1779         case 'h': {
1780             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1781             return OHOS::ERR_INVALID_VALUE;
1782         }
1783         case 'c': {
1784             std::string arrayJsonRule = optarg;
1785             std::stringstream array(arrayJsonRule);
1786             std::string object;
1787             while (getline(array, object, ';')) {
1788                 size_t pos1 = object.find("appId");
1789                 size_t pos2 = object.find("controlMessage");
1790                 size_t pos3 = object.find(":", pos2);
1791                 if ((pos1 == std::string::npos) || (pos2 == std::string::npos)) {
1792                     return OHOS::ERR_INVALID_VALUE;
1793                 }
1794                 std::string appId = object.substr(pos1+6, pos2-pos1-7);
1795                 std::string controlMessage = object.substr(pos3+1);
1796                 AppRunningControlRule rule;
1797                 rule.appId = appId;
1798                 rule.controlMessage = controlMessage;
1799                 controlRule.emplace_back(rule);
1800             }
1801             break;
1802         }
1803         case 'e': {
1804             StringToInt(optarg, commandName, euid, ret);
1805             break;
1806         }
1807         case 'u': {
1808             StringToInt(optarg, commandName, userId, ret);
1809             break;
1810         }
1811         default: {
1812             std::string unknownOption = "";
1813             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1814             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1815             resultReceiver_.append(unknownOptionMsg);
1816             return OHOS::ERR_INVALID_VALUE;
1817         }
1818     }
1819     return OHOS::ERR_OK;
1820 }
1821 
1822 // bundle_test_tool addAppRunningRule -c appId:id1,controlMessage:msg1;appId:id2,controlMessage:msg2
1823 // -u 101 -e 537
RunAsAddAppRunningRuleCommand()1824 ErrCode BundleTestTool::RunAsAddAppRunningRuleCommand()
1825 {
1826     ErrCode result = OHOS::ERR_OK;
1827     int counter = 0;
1828     int euid = 537;
1829     std::string commandName = "addAppRunningRule";
1830     int userId = 100;
1831     std::vector<AppRunningControlRule> controlRule;
1832     APP_LOGD("RunAsAddAppRunningRuleCommand is start");
1833     while (true) {
1834         counter++;
1835         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1836         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1837         if (optind < 0 || optind > argc_) {
1838             return OHOS::ERR_INVALID_VALUE;
1839         }
1840         if (option == -1) {
1841             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1842                 APP_LOGD("bundle_test_tool getRule with no option.");
1843                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
1844                 return OHOS::ERR_INVALID_VALUE;
1845             }
1846             break;
1847         }
1848         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
1849         if (result != OHOS::ERR_OK) {
1850             resultReceiver_.append(HELP_MSG_ADD_APP_RUNNING_RULE);
1851             return OHOS::ERR_INVALID_VALUE;
1852         }
1853     }
1854     seteuid(euid);
1855     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1856     if (!appControlProxy) {
1857         APP_LOGE("fail to get app control proxy.");
1858         return OHOS::ERR_INVALID_VALUE;
1859     }
1860     std::string appIdParam = "";
1861     for (auto param : controlRule) {
1862         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
1863     }
1864     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
1865     int32_t res = appControlProxy->AddAppRunningControlRule(controlRule, userId);
1866     if (res != OHOS::ERR_OK) {
1867         resultReceiver_.append(STRING_ADD_RULE_NG);
1868         return res;
1869     }
1870     resultReceiver_.append(std::to_string(res) + "\n");
1871     return result;
1872 }
1873 
1874 // bundle_test_tool deleteAppRunningRule -c appId:101,controlMessage:msg1 -u 101 -e 537
RunAsDeleteAppRunningRuleCommand()1875 ErrCode BundleTestTool::RunAsDeleteAppRunningRuleCommand()
1876 {
1877     ErrCode result = OHOS::ERR_OK;
1878     int counter = 0;
1879     int euid = 537;
1880     std::string commandName = "addAppRunningRule";
1881     int userId = 100;
1882     std::vector<AppRunningControlRule> controlRule;
1883     APP_LOGD("RunAsDeleteAppRunningRuleCommand is start");
1884     while (true) {
1885         counter++;
1886         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1887         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1888         if (optind < 0 || optind > argc_) {
1889             return OHOS::ERR_INVALID_VALUE;
1890         }
1891         if (option == -1) {
1892             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1893                 APP_LOGD("bundle_test_tool getRule with no option.");
1894                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
1895                 return OHOS::ERR_INVALID_VALUE;
1896             }
1897             break;
1898         }
1899         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
1900         if (result != OHOS::ERR_OK) {
1901             resultReceiver_.append(HELP_MSG_DELETE_APP_RUNNING_RULE);
1902             return OHOS::ERR_INVALID_VALUE;
1903         }
1904     }
1905     seteuid(euid);
1906     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1907     if (!appControlProxy) {
1908         APP_LOGE("fail to get app control proxy.");
1909         return OHOS::ERR_INVALID_VALUE;
1910     }
1911     std::string appIdParam = "";
1912     for (auto param : controlRule) {
1913         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
1914     }
1915     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
1916     int32_t res = appControlProxy->DeleteAppRunningControlRule(controlRule, userId);
1917     if (res != OHOS::ERR_OK) {
1918         resultReceiver_.append(STRING_DELETE_RULE_NG);
1919         return res;
1920     }
1921     resultReceiver_.append(std::to_string(res) + "\n");
1922     return result;
1923 }
1924 
CheckCleanAppRunningRuleCorrectOption(int option,const std::string & commandName,int & userId,int & euid)1925 ErrCode BundleTestTool::CheckCleanAppRunningRuleCorrectOption(
1926     int option, const std::string &commandName, int &userId, int &euid)
1927 {
1928     bool ret = true;
1929     switch (option) {
1930         case 'h': {
1931             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1932             return OHOS::ERR_INVALID_VALUE;
1933         }
1934         case 'e': {
1935             StringToInt(optarg, commandName, euid, ret);
1936             break;
1937         }
1938         case 'u': {
1939             StringToInt(optarg, commandName, userId, ret);
1940             break;
1941         }
1942         default: {
1943             std::string unknownOption = "";
1944             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1945             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1946             resultReceiver_.append(unknownOptionMsg);
1947             return OHOS::ERR_INVALID_VALUE;
1948         }
1949     }
1950     return OHOS::ERR_OK;
1951 }
1952 
1953 // bundle_test_tool cleanAppRunningRule -u 101 -e 537
RunAsCleanAppRunningRuleCommand()1954 ErrCode BundleTestTool::RunAsCleanAppRunningRuleCommand()
1955 {
1956     ErrCode result = OHOS::ERR_OK;
1957     int counter = 0;
1958     int euid = 537;
1959     std::string commandName = "addAppRunningRule";
1960     int userId = 100;
1961     APP_LOGD("RunAsCleanAppRunningRuleCommand is start");
1962     while (true) {
1963         counter++;
1964         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
1965         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1966         if (optind < 0 || optind > argc_) {
1967             return OHOS::ERR_INVALID_VALUE;
1968         }
1969         if (option == -1) {
1970             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1971                 APP_LOGD("bundle_test_tool getRule with no option.");
1972                 resultReceiver_.append(HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION);
1973                 return OHOS::ERR_INVALID_VALUE;
1974             }
1975             break;
1976         }
1977         result = CheckCleanAppRunningRuleCorrectOption(option, commandName, userId, euid);
1978         if (result != OHOS::ERR_OK) {
1979             resultReceiver_.append(HELP_MSG_CLEAN_APP_RUNNING_RULE);
1980             return OHOS::ERR_INVALID_VALUE;
1981         }
1982     }
1983     seteuid(euid);
1984     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
1985     if (!appControlProxy) {
1986         APP_LOGE("fail to get app control proxy.");
1987         return OHOS::ERR_INVALID_VALUE;
1988     }
1989     APP_LOGI("userId: %{public}d", userId);
1990     int32_t res = appControlProxy->DeleteAppRunningControlRule(userId);
1991     if (res != OHOS::ERR_OK) {
1992         resultReceiver_.append(STRING_DELETE_RULE_NG);
1993         return res;
1994     }
1995     resultReceiver_.append(std::to_string(res) + "\n");
1996     return result;
1997 }
1998 
CheckGetAppRunningRuleCorrectOption(int option,const std::string & commandName,int32_t & userId,int & euid)1999 ErrCode BundleTestTool::CheckGetAppRunningRuleCorrectOption(int option, const std::string &commandName,
2000     int32_t &userId, int &euid)
2001 {
2002     bool ret = true;
2003     switch (option) {
2004         case 'h': {
2005             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2006             return OHOS::ERR_INVALID_VALUE;
2007         }
2008         case 'e': {
2009             StringToInt(optarg, commandName, euid, ret);
2010             break;
2011         }
2012         case 'u': {
2013             StringToInt(optarg, commandName, userId, ret);
2014             break;
2015         }
2016         default: {
2017             std::string unknownOption = "";
2018             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2019             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2020             resultReceiver_.append(unknownOptionMsg);
2021             return OHOS::ERR_INVALID_VALUE;
2022         }
2023     }
2024     return OHOS::ERR_OK ;
2025 }
2026 
2027 // bundle_test_tool getAppRunningControlRule -u 101 -e 537
RunAsGetAppRunningControlRuleCommand()2028 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleCommand()
2029 {
2030     ErrCode result = OHOS::ERR_OK;
2031     int counter = 0;
2032     int euid = 537;
2033     std::string commandName = "addAppRunningRule";
2034     int userId = 100;
2035     APP_LOGD("RunAsGetAppRunningControlRuleCommand is start");
2036     while (true) {
2037         counter++;
2038         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2039         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2040         if (optind < 0 || optind > argc_) {
2041             return OHOS::ERR_INVALID_VALUE;
2042         }
2043         if (option == -1) {
2044             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2045                 APP_LOGD("bundle_test_tool getRule with no option.");
2046                 resultReceiver_.append(HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION);
2047                 return OHOS::ERR_INVALID_VALUE;
2048             }
2049             break;
2050         }
2051         result = CheckGetAppRunningRuleCorrectOption(option, commandName, userId, euid);
2052         if (result != OHOS::ERR_OK) {
2053             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RULE);
2054             return OHOS::ERR_INVALID_VALUE;
2055         }
2056     }
2057     seteuid(euid);
2058     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2059     if (!appControlProxy) {
2060         APP_LOGE("fail to get app control proxy.");
2061         return OHOS::ERR_INVALID_VALUE;
2062     }
2063     APP_LOGI("userId: %{public}d", userId);
2064     std::vector<std::string> appIds;
2065     int32_t res = appControlProxy->GetAppRunningControlRule(userId, appIds);
2066     if (res != OHOS::ERR_OK) {
2067         resultReceiver_.append(STRING_GET_RULE_NG);
2068         return res;
2069     }
2070     std::string appIdParam = "";
2071     for (auto param : appIds) {
2072         appIdParam = appIdParam.append(param) + "; ";
2073     }
2074     resultReceiver_.append("appId : " + appIdParam + "\n");
2075     return result;
2076 }
2077 
CheckGetAppRunningRuleResultCorrectOption(int option,const std::string & commandName,std::string & bundleName,int32_t & userId,int & euid)2078 ErrCode BundleTestTool::CheckGetAppRunningRuleResultCorrectOption(int option, const std::string &commandName,
2079     std::string &bundleName, int32_t &userId, int &euid)
2080 {
2081     bool ret = true;
2082     switch (option) {
2083         case 'h': {
2084             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2085             return OHOS::ERR_INVALID_VALUE;
2086         }
2087         case 'e': {
2088             StringToInt(optarg, commandName, euid, ret);
2089             break;
2090         }
2091         case 'n': {
2092             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
2093             bundleName = optarg;
2094             break;
2095         }
2096         case 'u': {
2097             StringToInt(optarg, commandName, userId, ret);
2098             break;
2099         }
2100         default: {
2101             std::string unknownOption = "";
2102             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2103             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2104             resultReceiver_.append(unknownOptionMsg);
2105             return OHOS::ERR_INVALID_VALUE;
2106         }
2107     }
2108     return OHOS::ERR_OK;
2109 }
2110 
2111 // bundle_test_tool getAppRunningControlRuleResult -n com.ohos.example -e 537
RunAsGetAppRunningControlRuleResultCommand()2112 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleResultCommand()
2113 {
2114     ErrCode result = OHOS::ERR_OK;
2115     int counter = 0;
2116     int euid = 537;
2117     std::string commandName = "addAppRunningRule";
2118     int userId = 100;
2119     std::string bundleName;
2120     APP_LOGD("RunAsGetAppRunningControlRuleResultCommand is start");
2121     while (true) {
2122         counter++;
2123         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2124         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2125         if (optind < 0 || optind > argc_) {
2126             return OHOS::ERR_INVALID_VALUE;
2127         }
2128         if (option == -1) {
2129             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2130                 APP_LOGD("bundle_test_tool getRule with no option.");
2131                 resultReceiver_.append(HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION);
2132                 return OHOS::ERR_INVALID_VALUE;
2133             }
2134             break;
2135         }
2136         result = CheckGetAppRunningRuleResultCorrectOption(option, commandName, bundleName, userId, euid);
2137         if (result != OHOS::ERR_OK) {
2138             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RESULT_RULE);
2139             return OHOS::ERR_INVALID_VALUE;
2140         }
2141     }
2142     seteuid(euid);
2143     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2144     if (!appControlProxy) {
2145         APP_LOGE("fail to get app control proxy.");
2146         return OHOS::ERR_INVALID_VALUE;
2147     }
2148     AppRunningControlRuleResult ruleResult;
2149     APP_LOGI("bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
2150     int32_t res = appControlProxy->GetAppRunningControlRule(bundleName, userId, ruleResult);
2151     if (res != OHOS::ERR_OK) {
2152         APP_LOGI("GetAppRunningControlRule result: %{public}d", res);
2153         resultReceiver_.append("message:" + ruleResult.controlMessage + " bundle:notFind" + "\n");
2154         return res;
2155     }
2156     resultReceiver_.append("message:" + ruleResult.controlMessage + "\n");
2157     if (ruleResult.controlWant != nullptr) {
2158         resultReceiver_.append("controlWant:" + ruleResult.controlWant->ToString() + "\n");
2159     } else {
2160         resultReceiver_.append("controlWant: nullptr \n");
2161     }
2162     return result;
2163 }
2164 
RunAsDeployQuickFix()2165 ErrCode BundleTestTool::RunAsDeployQuickFix()
2166 {
2167     int32_t result = OHOS::ERR_OK;
2168     int32_t counter = 0;
2169     int32_t index = 0;
2170     std::vector<std::string> quickFixPaths;
2171     while (true) {
2172         counter++;
2173         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
2174         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2175         if (optind < 0 || optind > argc_) {
2176             return OHOS::ERR_INVALID_VALUE;
2177         }
2178 
2179         if (option == -1 || option == '?') {
2180             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
2181                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
2182                 result = OHOS::ERR_INVALID_VALUE;
2183                 break;
2184             }
2185             if (optopt == 'p') {
2186                 // 'bm deployQuickFix --patch-path' with no argument
2187                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2188                 result = OHOS::ERR_INVALID_VALUE;
2189                 break;
2190             }
2191             break;
2192         }
2193 
2194         if (option == 'p') {
2195             APP_LOGD("'bm deployQuickFix -p %{public}s'", argv_[optind - 1]);
2196             quickFixPaths.emplace_back(optarg);
2197             index = optind;
2198             continue;
2199         }
2200         result = OHOS::ERR_INVALID_VALUE;
2201         break;
2202     }
2203 
2204     if (result != OHOS::ERR_OK || GetQuickFixPath(index, quickFixPaths) != OHOS::ERR_OK) {
2205         resultReceiver_.append(HELP_MSG_DEPLOY_QUICK_FIX);
2206         return result;
2207     }
2208 
2209     std::shared_ptr<QuickFixResult> deployRes = nullptr;
2210     result = DeployQuickFix(quickFixPaths, deployRes);
2211     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DEPLOY_QUICK_FIX_OK : STRING_DEPLOY_QUICK_FIX_NG;
2212     resultReceiver_ += GetResMsg(result, deployRes);
2213 
2214     return result;
2215 }
2216 
GetQuickFixPath(int32_t index,std::vector<std::string> & quickFixPaths) const2217 ErrCode BundleTestTool::GetQuickFixPath(int32_t index, std::vector<std::string>& quickFixPaths) const
2218 {
2219     APP_LOGI("GetQuickFixPath start");
2220     for (; index < argc_ && index >= INDEX_OFFSET; ++index) {
2221         if (argList_[index - INDEX_OFFSET] == "-p" || argList_[index - INDEX_OFFSET] == "--patch-path") {
2222             break;
2223         }
2224 
2225         std::string innerPath = argList_[index - INDEX_OFFSET];
2226         if (innerPath.empty() || innerPath == "-p" || innerPath == "--patch-path") {
2227             quickFixPaths.clear();
2228             return OHOS::ERR_INVALID_VALUE;
2229         }
2230         APP_LOGD("GetQuickFixPath is %{public}s'", innerPath.c_str());
2231         quickFixPaths.emplace_back(innerPath);
2232     }
2233     return OHOS::ERR_OK;
2234 }
2235 
RunAsSwitchQuickFix()2236 ErrCode BundleTestTool::RunAsSwitchQuickFix()
2237 {
2238     int32_t result = OHOS::ERR_OK;
2239     int32_t counter = 0;
2240     int32_t enable = -1;
2241     std::string bundleName;
2242     while (true) {
2243         counter++;
2244         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
2245         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2246         if (optind < 0 || optind > argc_) {
2247             return OHOS::ERR_INVALID_VALUE;
2248         }
2249 
2250         if (option == -1 || option == '?') {
2251             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
2252                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
2253                 result = OHOS::ERR_INVALID_VALUE;
2254                 break;
2255             }
2256             if (optopt == 'n' || optopt == 'e') {
2257                 // 'bm switchQuickFix -n -e' with no argument
2258                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2259                 result = OHOS::ERR_INVALID_VALUE;
2260                 break;
2261             }
2262             break;
2263         }
2264 
2265         if (option == 'n') {
2266             APP_LOGD("'bm switchQuickFix -n %{public}s'", argv_[optind - 1]);
2267             bundleName = optarg;
2268             continue;
2269         }
2270         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
2271             APP_LOGD("'bm switchQuickFix -e %{public}s'", argv_[optind - 1]);
2272             continue;
2273         }
2274         result = OHOS::ERR_INVALID_VALUE;
2275         break;
2276     }
2277 
2278     if ((result != OHOS::ERR_OK) || (enable < 0) || (enable > 1)) {
2279         resultReceiver_.append(HELP_MSG_SWITCH_QUICK_FIX);
2280         return result;
2281     }
2282     std::shared_ptr<QuickFixResult> switchRes = nullptr;
2283     result = SwitchQuickFix(bundleName, enable, switchRes);
2284     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_SWITCH_QUICK_FIX_OK : STRING_SWITCH_QUICK_FIX_NG;
2285     resultReceiver_ += GetResMsg(result, switchRes);
2286 
2287     return result;
2288 }
2289 
RunAsDeleteQuickFix()2290 ErrCode BundleTestTool::RunAsDeleteQuickFix()
2291 {
2292     int32_t result = OHOS::ERR_OK;
2293     int32_t counter = 0;
2294     std::string bundleName;
2295     while (true) {
2296         counter++;
2297         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
2298         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2299         if (optind < 0 || optind > argc_) {
2300             return OHOS::ERR_INVALID_VALUE;
2301         }
2302 
2303         if (option == -1 || option == '?') {
2304             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
2305                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
2306                 result = OHOS::ERR_INVALID_VALUE;
2307                 break;
2308             }
2309             if (optopt == 'n') {
2310                 // 'bm deleteQuickFix -n' with no argument
2311                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2312                 result = OHOS::ERR_INVALID_VALUE;
2313                 break;
2314             }
2315             break;
2316         }
2317 
2318         if (option == 'n') {
2319             APP_LOGD("'bm deleteQuickFix -n %{public}s'", argv_[optind - 1]);
2320             bundleName = optarg;
2321             continue;
2322         }
2323         result = OHOS::ERR_INVALID_VALUE;
2324         break;
2325     }
2326 
2327     if (result != OHOS::ERR_OK) {
2328         resultReceiver_.append(HELP_MSG_SWITCH_QUICK_FIX);
2329         return result;
2330     }
2331     std::shared_ptr<QuickFixResult> deleteRes = nullptr;
2332     result = DeleteQuickFix(bundleName, deleteRes);
2333     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DELETE_QUICK_FIX_OK : STRING_DELETE_QUICK_FIX_NG;
2334     resultReceiver_ += GetResMsg(result, deleteRes);
2335 
2336     return result;
2337 }
2338 
DeployQuickFix(const std::vector<std::string> & quickFixPaths,std::shared_ptr<QuickFixResult> & quickFixRes)2339 ErrCode BundleTestTool::DeployQuickFix(const std::vector<std::string> &quickFixPaths,
2340     std::shared_ptr<QuickFixResult> &quickFixRes)
2341 {
2342 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2343     std::set<std::string> realPathSet;
2344     for (const auto &quickFixPath : quickFixPaths) {
2345         std::string realPath;
2346         if (!PathToRealPath(quickFixPath, realPath)) {
2347             APP_LOGW("quickFixPath %{public}s is invalid", quickFixPath.c_str());
2348             continue;
2349         }
2350         APP_LOGD("realPath is %{public}s", realPath.c_str());
2351         realPathSet.insert(realPath);
2352     }
2353     std::vector<std::string> pathVec(realPathSet.begin(), realPathSet.end());
2354 
2355     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
2356     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
2357         APP_LOGE("callback or bundleMgrProxy is null");
2358         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2359     }
2360     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
2361     if (recipient == nullptr) {
2362         APP_LOGE("recipient is null");
2363         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2364     }
2365     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
2366     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
2367     if (quickFixProxy == nullptr) {
2368         APP_LOGE("quickFixProxy is null");
2369         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2370     }
2371     std::vector<std::string> destFiles;
2372     auto res = quickFixProxy->CopyFiles(pathVec, destFiles);
2373     if (res != ERR_OK) {
2374         APP_LOGE("Copy files failed with %{public}d.", res);
2375         return res;
2376     }
2377     res = quickFixProxy->DeployQuickFix(destFiles, callback);
2378     if (res != ERR_OK) {
2379         APP_LOGE("DeployQuickFix failed");
2380         return res;
2381     }
2382 
2383     return callback->GetResultCode(quickFixRes);
2384 #else
2385     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
2386 #endif
2387 }
2388 
SwitchQuickFix(const std::string & bundleName,int32_t enable,std::shared_ptr<QuickFixResult> & quickFixRes)2389 ErrCode BundleTestTool::SwitchQuickFix(const std::string &bundleName, int32_t enable,
2390     std::shared_ptr<QuickFixResult> &quickFixRes)
2391 {
2392     APP_LOGD("SwitchQuickFix bundleName: %{public}s, enable: %{public}d", bundleName.c_str(), enable);
2393 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2394     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
2395     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
2396         APP_LOGE("callback or bundleMgrProxy is null");
2397         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2398     }
2399     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
2400     if (recipient == nullptr) {
2401         APP_LOGE("recipient is null");
2402         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2403     }
2404     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
2405     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
2406     if (quickFixProxy == nullptr) {
2407         APP_LOGE("quickFixProxy is null");
2408         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2409     }
2410     bool enableFlag = (enable == 0) ? false : true;
2411     auto res = quickFixProxy->SwitchQuickFix(bundleName, enableFlag, callback);
2412     if (res != ERR_OK) {
2413         APP_LOGE("SwitchQuickFix failed");
2414         return res;
2415     }
2416     return callback->GetResultCode(quickFixRes);
2417 #else
2418     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
2419 #endif
2420 }
2421 
DeleteQuickFix(const std::string & bundleName,std::shared_ptr<QuickFixResult> & quickFixRes)2422 ErrCode BundleTestTool::DeleteQuickFix(const std::string &bundleName,
2423     std::shared_ptr<QuickFixResult> &quickFixRes)
2424 {
2425     APP_LOGD("DeleteQuickFix bundleName: %{public}s", bundleName.c_str());
2426 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
2427     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
2428     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
2429         APP_LOGE("callback or bundleMgrProxy is null");
2430         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2431     }
2432     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
2433     if (recipient == nullptr) {
2434         APP_LOGE("recipient is null");
2435         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2436     }
2437     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
2438     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
2439     if (quickFixProxy == nullptr) {
2440         APP_LOGE("quickFixProxy is null");
2441         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
2442     }
2443     auto res = quickFixProxy->DeleteQuickFix(bundleName, callback);
2444     if (res != ERR_OK) {
2445         APP_LOGE("DeleteQuickFix failed");
2446         return res;
2447     }
2448     return callback->GetResultCode(quickFixRes);
2449 #else
2450     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
2451 #endif
2452 }
2453 
GetResMsg(int32_t code)2454 std::string BundleTestTool::GetResMsg(int32_t code)
2455 {
2456     std::unordered_map<int32_t, std::string> quickFixMsgMap;
2457     CreateQuickFixMsgMap(quickFixMsgMap);
2458     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
2459         return quickFixMsgMap.at(code);
2460     }
2461     return MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
2462 }
2463 
GetResMsg(int32_t code,const std::shared_ptr<QuickFixResult> & quickFixRes)2464 std::string BundleTestTool::GetResMsg(int32_t code, const std::shared_ptr<QuickFixResult> &quickFixRes)
2465 {
2466     std::string resMsg;
2467     std::unordered_map<int32_t, std::string> quickFixMsgMap;
2468     CreateQuickFixMsgMap(quickFixMsgMap);
2469     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
2470         resMsg += quickFixMsgMap.at(code);
2471     } else {
2472         resMsg += MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
2473     }
2474     if (quickFixRes != nullptr) {
2475         resMsg += quickFixRes->ToString() + "\n";
2476     }
2477     return resMsg;
2478 }
2479 
RunAsSetDebugMode()2480 ErrCode BundleTestTool::RunAsSetDebugMode()
2481 {
2482     int32_t result = OHOS::ERR_OK;
2483     int32_t counter = 0;
2484     int32_t enable = -1;
2485     while (true) {
2486         counter++;
2487         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_DEBUG_MODE.c_str(), LONG_OPTIONS_DEBUG_MODE, nullptr);
2488         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2489         if (optind < 0 || optind > argc_) {
2490             return OHOS::ERR_INVALID_VALUE;
2491         }
2492 
2493         if (option == -1 || option == '?') {
2494             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
2495                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
2496                 result = OHOS::ERR_INVALID_VALUE;
2497                 break;
2498             }
2499             if (optopt == 'e') {
2500                 // 'bundle_test_tool setDebugMode -e' with no argument
2501                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2502                 result = OHOS::ERR_INVALID_VALUE;
2503                 break;
2504             }
2505             break;
2506         }
2507 
2508         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
2509             APP_LOGD("'bundle_test_tool setDebugMode -e %{public}s'", argv_[optind - 1]);
2510             continue;
2511         }
2512         result = OHOS::ERR_INVALID_VALUE;
2513         break;
2514     }
2515 
2516     if (result != OHOS::ERR_OK) {
2517         resultReceiver_.append(HELP_MSG_SET_DEBUG_MODE);
2518         return result;
2519     }
2520     ErrCode setResult = SetDebugMode(enable);
2521     if (setResult == OHOS::ERR_OK) {
2522         resultReceiver_ = STRING_SET_DEBUG_MODE_OK;
2523     } else {
2524         resultReceiver_ = STRING_SET_DEBUG_MODE_NG + GetResMsg(setResult);
2525     }
2526     return setResult;
2527 }
2528 
SetDebugMode(int32_t debugMode)2529 ErrCode BundleTestTool::SetDebugMode(int32_t debugMode)
2530 {
2531     if (debugMode != 0 && debugMode != 1) {
2532         APP_LOGE("SetDebugMode param is invalid");
2533         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM;
2534     }
2535     bool enable = debugMode == 0 ? false : true;
2536     if (bundleMgrProxy_ == nullptr) {
2537         APP_LOGE("bundleMgrProxy_ is nullptr");
2538         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR;
2539     }
2540     return bundleMgrProxy_->SetDebugMode(enable);
2541 }
2542 
RunAsGetBundleStats()2543 ErrCode BundleTestTool::RunAsGetBundleStats()
2544 {
2545     int32_t result = OHOS::ERR_OK;
2546     int32_t counter = 0;
2547     std::string bundleName = "";
2548     int32_t userId = Constants::UNSPECIFIED_USERID;
2549     while (true) {
2550         counter++;
2551         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLE_STATS.c_str(),
2552             LONG_OPTIONS_GET_BUNDLE_STATS, nullptr);
2553         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2554         if (optind < 0 || optind > argc_) {
2555             return OHOS::ERR_INVALID_VALUE;
2556         }
2557         if (option == -1) {
2558             if (counter == 1) {
2559                 // When scanning the first argument
2560                 if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
2561                     resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
2562                     result = OHOS::ERR_INVALID_VALUE;
2563                 }
2564             }
2565             break;
2566         }
2567 
2568         if (option == '?') {
2569             switch (optopt) {
2570                 case 'n': {
2571                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2572                     result = OHOS::ERR_INVALID_VALUE;
2573                     break;
2574                 }
2575                 case 'u': {
2576                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2577                     result = OHOS::ERR_INVALID_VALUE;
2578                     break;
2579                 }
2580                 default: {
2581                     std::string unknownOption = "";
2582                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2583                     resultReceiver_.append(unknownOptionMsg);
2584                     result = OHOS::ERR_INVALID_VALUE;
2585                     break;
2586                 }
2587             }
2588             break;
2589         }
2590 
2591         switch (option) {
2592             case 'h': {
2593                 result = OHOS::ERR_INVALID_VALUE;
2594                 break;
2595             }
2596             case 'n': {
2597                 bundleName = optarg;
2598                 break;
2599             }
2600             case 'u': {
2601                 if (!OHOS::StrToInt(optarg, userId) || userId < 0) {
2602                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
2603                     return OHOS::ERR_INVALID_VALUE;
2604                 }
2605                 break;
2606             }
2607             default: {
2608                 result = OHOS::ERR_INVALID_VALUE;
2609                 break;
2610             }
2611         }
2612     }
2613 
2614     if (result == OHOS::ERR_OK) {
2615         if (resultReceiver_ == "" && bundleName.size() == 0) {
2616             resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION + "\n");
2617             result = OHOS::ERR_INVALID_VALUE;
2618         }
2619     }
2620 
2621     if (result != OHOS::ERR_OK) {
2622         resultReceiver_.append(HELP_MSG_GET_BUNDLE_STATS);
2623     } else {
2624         std::string msg;
2625         bool ret = GetBundleStats(bundleName, userId, msg);
2626         if (ret) {
2627             resultReceiver_ = STRING_GET_BUNDLE_STATS_OK + msg;
2628         } else {
2629             resultReceiver_ = STRING_GET_BUNDLE_STATS_NG + "\n";
2630         }
2631     }
2632 
2633     return result;
2634 }
2635 
GetBundleStats(const std::string & bundleName,int32_t userId,std::string & msg)2636 bool BundleTestTool::GetBundleStats(const std::string &bundleName, int32_t userId,
2637     std::string& msg)
2638 {
2639     if (bundleMgrProxy_ == nullptr) {
2640         APP_LOGE("bundleMgrProxy_ is nullptr");
2641         return false;
2642     }
2643     userId = BundleCommandCommon::GetCurrentUserId(userId);
2644     std::vector<std::int64_t> bundleStats;
2645     bool ret = bundleMgrProxy_->GetBundleStats(bundleName, userId, bundleStats);
2646     if (ret) {
2647         for (size_t index = 0; index < bundleStats.size(); ++index) {
2648             msg += GET_BUNDLE_STATS_ARRAY[index] + std::to_string(bundleStats[index]) + "\n";
2649         }
2650     }
2651     return ret;
2652 }
2653 } // AppExecFwk
2654 } // OHOS