• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "adb_install.h"
18 
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <algorithm>
25 #include <string>
26 #include <string_view>
27 #include <vector>
28 
29 #include <android-base/file.h>
30 #include <android-base/parsebool.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/strings.h>
33 
34 #include "adb.h"
35 #include "adb_client.h"
36 #include "adb_unique_fd.h"
37 #include "adb_utils.h"
38 #include "client/file_sync_client.h"
39 #include "commandline.h"
40 #include "fastdeploy.h"
41 #include "incremental.h"
42 #include "sysdeps.h"
43 
44 using namespace std::literals;
45 
46 static constexpr int kFastDeployMinApi = 24;
47 
48 namespace {
49 
50 enum InstallMode {
51     INSTALL_DEFAULT,
52     INSTALL_PUSH,
53     INSTALL_STREAM,
54     INSTALL_INCREMENTAL,
55 };
56 
57 enum class CmdlineOption { None, Enable, Disable };
58 }
59 
best_install_mode()60 static InstallMode best_install_mode() {
61     auto&& features = adb_get_feature_set_or_die();
62     if (CanUseFeature(*features, kFeatureCmd)) {
63         return INSTALL_STREAM;
64     }
65     return INSTALL_PUSH;
66 }
67 
is_apex_supported()68 static bool is_apex_supported() {
69     auto&& features = adb_get_feature_set_or_die();
70     return CanUseFeature(*features, kFeatureApex);
71 }
72 
is_abb_exec_supported()73 static bool is_abb_exec_supported() {
74     auto&& features = adb_get_feature_set_or_die();
75     return CanUseFeature(*features, kFeatureAbbExec);
76 }
77 
pm_command(int argc,const char ** argv)78 static int pm_command(int argc, const char** argv) {
79     std::string cmd = "pm";
80 
81     while (argc-- > 0) {
82         cmd += " " + escape_arg(*argv++);
83     }
84 
85     return send_shell_command(cmd);
86 }
87 
uninstall_app_streamed(int argc,const char ** argv)88 static int uninstall_app_streamed(int argc, const char** argv) {
89     // 'adb uninstall' takes the same arguments as 'cmd package uninstall' on device
90     std::string cmd = "cmd package";
91     while (argc-- > 0) {
92         // deny the '-k' option until the remaining data/cache can be removed with adb/UI
93         if (strcmp(*argv, "-k") == 0) {
94             printf("The -k option uninstalls the application while retaining the "
95                    "data/cache.\n"
96                    "At the moment, there is no way to remove the remaining data.\n"
97                    "You will have to reinstall the application with the same "
98                    "signature, and fully "
99                    "uninstall it.\n"
100                    "If you truly wish to continue, execute 'adb shell cmd package "
101                    "uninstall -k'.\n");
102             return EXIT_FAILURE;
103         }
104         cmd += " " + escape_arg(*argv++);
105     }
106 
107     return send_shell_command(cmd);
108 }
109 
uninstall_app_legacy(int argc,const char ** argv)110 static int uninstall_app_legacy(int argc, const char** argv) {
111     /* if the user choose the -k option, we refuse to do it until devices are
112        out with the option to uninstall the remaining data somehow (adb/ui) */
113     for (int i = 1; i < argc; i++) {
114         if (!strcmp(argv[i], "-k")) {
115             printf("The -k option uninstalls the application while retaining the "
116                    "data/cache.\n"
117                    "At the moment, there is no way to remove the remaining data.\n"
118                    "You will have to reinstall the application with the same "
119                    "signature, and fully "
120                    "uninstall it.\n"
121                    "If you truly wish to continue, execute 'adb shell pm uninstall "
122                    "-k'\n.");
123             return EXIT_FAILURE;
124         }
125     }
126 
127     /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */
128     return pm_command(argc, argv);
129 }
130 
uninstall_app(int argc,const char ** argv)131 int uninstall_app(int argc, const char** argv) {
132     if (best_install_mode() == INSTALL_PUSH) {
133         return uninstall_app_legacy(argc, argv);
134     }
135     return uninstall_app_streamed(argc, argv);
136 }
137 
read_status_line(int fd,char * buf,size_t count)138 static void read_status_line(int fd, char* buf, size_t count) {
139     count--;
140     while (count > 0) {
141         int len = adb_read(fd, buf, count);
142         if (len <= 0) {
143             break;
144         }
145 
146         buf += len;
147         count -= len;
148     }
149     *buf = '\0';
150 }
151 
send_command(const std::vector<std::string> & cmd_args,std::string * error)152 static unique_fd send_command(const std::vector<std::string>& cmd_args, std::string* error) {
153     VLOG(ADB) << "pm command: '" << android::base::Join(cmd_args, " ") << "'";
154     if (is_abb_exec_supported()) {
155         return send_abb_exec_command(cmd_args, error);
156     } else {
157         return unique_fd(adb_connect(android::base::Join(cmd_args, " "), error));
158     }
159 }
160 
install_app_streamed(int argc,const char ** argv,bool use_fastdeploy)161 static int install_app_streamed(int argc, const char** argv, bool use_fastdeploy) {
162     printf("Performing Streamed Install\n");
163 
164     // The last argument must be the APK file
165     const char* file = argv[argc - 1];
166     if (!android::base::EndsWithIgnoreCase(file, ".apk") &&
167         !android::base::EndsWithIgnoreCase(file, ".apex")) {
168         error_exit("filename doesn't end .apk or .apex: %s", file);
169     }
170 
171     bool is_apex = false;
172     if (android::base::EndsWithIgnoreCase(file, ".apex")) {
173         is_apex = true;
174     }
175     if (is_apex && !is_apex_supported()) {
176         error_exit(".apex is not supported on the target device");
177     }
178 
179     if (is_apex && use_fastdeploy) {
180         error_exit("--fastdeploy doesn't support .apex files");
181     }
182 
183     if (use_fastdeploy) {
184         auto metadata = extract_metadata(file);
185         if (metadata.has_value()) {
186             // pass all but 1st (command) and last (apk path) parameters through to pm for
187             // session creation
188             std::vector<const char*> pm_args{argv + 1, argv + argc - 1};
189             auto patchFd = install_patch(pm_args.size(), pm_args.data());
190             return stream_patch(file, std::move(metadata.value()), std::move(patchFd));
191         }
192     }
193 
194     struct stat sb;
195     if (stat(file, &sb) == -1) {
196         perror_exit("failed to stat %s", file);
197     }
198 
199     unique_fd local_fd(adb_open(file, O_RDONLY | O_CLOEXEC));
200     if (local_fd < 0) {
201         perror_exit("failed to open %s", file);
202     }
203 
204 #ifdef __linux__
205     posix_fadvise(local_fd.get(), 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
206 #endif
207 
208     const bool use_abb_exec = is_abb_exec_supported();
209     std::string error;
210     std::vector<std::string> cmd_args = {use_abb_exec ? "package" : "exec:cmd package"};
211     cmd_args.reserve(argc + 3);
212 
213     // don't copy the APK name, but, copy the rest of the arguments as-is
214     while (argc-- > 1) {
215         if (use_abb_exec) {
216             cmd_args.push_back(*argv++);
217         } else {
218             cmd_args.push_back(escape_arg(*argv++));
219         }
220     }
221 
222     // add size parameter [required for streaming installs]
223     // do last to override any user specified value
224     cmd_args.push_back("-S");
225     cmd_args.push_back(android::base::StringPrintf("%" PRIu64, static_cast<uint64_t>(sb.st_size)));
226 
227     if (is_apex) {
228         cmd_args.push_back("--apex");
229     }
230 
231     unique_fd remote_fd = send_command(cmd_args, &error);
232     if (remote_fd < 0) {
233         error_exit("connect error for write: %s", error.c_str());
234     }
235 
236     if (!copy_to_file(local_fd.get(), remote_fd.get())) {
237         perror_exit("failed to install: copy_to_file: %s", file);
238     }
239 
240     char buf[BUFSIZ];
241     read_status_line(remote_fd.get(), buf, sizeof(buf));
242     if (strncmp("Success", buf, 7) != 0) {
243         error_exit("failed to install %s: %s", file, buf);
244     }
245 
246     fputs(buf, stdout);
247     return 0;
248 }
249 
install_app_legacy(int argc,const char ** argv,bool use_fastdeploy)250 static int install_app_legacy(int argc, const char** argv, bool use_fastdeploy) {
251     printf("Performing Push Install\n");
252 
253     // Find last APK argument.
254     // All other arguments passed through verbatim.
255     int last_apk = -1;
256     for (int i = argc - 1; i >= 0; i--) {
257         if (android::base::EndsWithIgnoreCase(argv[i], ".apex")) {
258             error_exit("APEX packages are only compatible with Streamed Install");
259         }
260         if (android::base::EndsWithIgnoreCase(argv[i], ".apk")) {
261             last_apk = i;
262             break;
263         }
264     }
265 
266     if (last_apk == -1) error_exit("need APK file on command line");
267 
268     int result = -1;
269     std::vector<const char*> apk_file = {argv[last_apk]};
270     std::string apk_dest = "/data/local/tmp/" + android::base::Basename(argv[last_apk]);
271     argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
272 
273     if (use_fastdeploy) {
274         auto metadata = extract_metadata(apk_file[0]);
275         if (metadata.has_value()) {
276             auto patchFd = apply_patch_on_device(apk_dest.c_str());
277             int status = stream_patch(apk_file[0], std::move(metadata.value()), std::move(patchFd));
278 
279             result = pm_command(argc, argv);
280             delete_device_file(apk_dest);
281 
282             return status;
283         }
284     }
285 
286     if (do_sync_push(apk_file, apk_dest.c_str(), false, CompressionType::Any, false, false)) {
287         result = pm_command(argc, argv);
288         delete_device_file(apk_dest);
289     }
290 
291     return result;
292 }
293 
294 template <class TimePoint>
ms_between(TimePoint start,TimePoint end)295 static int ms_between(TimePoint start, TimePoint end) {
296     return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
297 }
298 
install_app_incremental(int argc,const char ** argv,bool wait,bool silent)299 static int install_app_incremental(int argc, const char** argv, bool wait, bool silent) {
300     using clock = std::chrono::high_resolution_clock;
301     const auto start = clock::now();
302     int first_apk = -1;
303     int last_apk = -1;
304     incremental::Args passthrough_args = {};
305     for (int i = 0; i < argc; ++i) {
306         const auto arg = std::string_view(argv[i]);
307         if (android::base::EndsWithIgnoreCase(arg, ".apk"sv)) {
308             last_apk = i;
309             if (first_apk == -1) {
310                 first_apk = i;
311             }
312         } else if (arg.starts_with("install"sv)) {
313             // incremental installation command on the device is the same for all its variations in
314             // the adb, e.g. install-multiple or install-multi-package
315         } else {
316             passthrough_args.push_back(arg);
317         }
318     }
319 
320     if (first_apk == -1) {
321         if (!silent) {
322             fprintf(stderr, "error: need at least one APK file on command line\n");
323         }
324         return -1;
325     }
326 
327     auto files = incremental::Files{argv + first_apk, argv + last_apk + 1};
328     if (silent) {
329         // For a silent installation we want to do the lightweight check first and bail early and
330         // quietly if it fails.
331         if (!incremental::can_install(files)) {
332             return -1;
333         }
334     }
335 
336     printf("Performing Incremental Install\n");
337     auto server_process = incremental::install(files, passthrough_args, silent);
338     if (!server_process) {
339         return -1;
340     }
341 
342     const auto end = clock::now();
343     printf("Install command complete in %d ms\n", ms_between(start, end));
344 
345     if (wait) {
346         (*server_process).wait();
347     }
348 
349     return 0;
350 }
351 
calculate_install_mode(InstallMode modeFromArgs,bool fastdeploy,CmdlineOption incremental_request)352 static std::pair<InstallMode, std::optional<InstallMode>> calculate_install_mode(
353         InstallMode modeFromArgs, bool fastdeploy, CmdlineOption incremental_request) {
354     if (incremental_request == CmdlineOption::Enable) {
355         if (fastdeploy) {
356             error_exit(
357                     "--incremental and --fast-deploy options are incompatible. "
358                     "Please choose one");
359         }
360     }
361 
362     if (modeFromArgs != INSTALL_DEFAULT) {
363         if (incremental_request == CmdlineOption::Enable) {
364             error_exit("--incremental is not compatible with other installation modes");
365         }
366         return {modeFromArgs, std::nullopt};
367     }
368 
369     if (incremental_request != CmdlineOption::Disable && !is_abb_exec_supported()) {
370         if (incremental_request == CmdlineOption::None) {
371             incremental_request = CmdlineOption::Disable;
372         } else {
373             error_exit("Device doesn't support incremental installations");
374         }
375     }
376     if (incremental_request == CmdlineOption::None) {
377         // check if the host is ok with incremental by default
378         if (const char* incrementalFromEnv = getenv("ADB_INSTALL_DEFAULT_INCREMENTAL")) {
379             using namespace android::base;
380             auto val = ParseBool(incrementalFromEnv);
381             if (val == ParseBoolResult::kFalse) {
382                 incremental_request = CmdlineOption::Disable;
383             }
384         }
385     }
386     if (incremental_request == CmdlineOption::None) {
387         // still ok: let's see if the device allows using incremental by default
388         // it starts feeling like we're looking for an excuse to not to use incremental...
389         std::string error;
390         std::vector<std::string> args = {"settings", "get", "global",
391                                          "enable_adb_incremental_install_default"};
392         auto fd = send_abb_exec_command(args, &error);
393         if (!fd.ok()) {
394             fprintf(stderr, "adb: retrieving the default device installation mode failed: %s\n",
395                     error.c_str());
396         } else {
397             char buf[BUFSIZ] = {};
398             read_status_line(fd.get(), buf, sizeof(buf));
399             using namespace android::base;
400             auto val = ParseBool(buf);
401             if (val == ParseBoolResult::kFalse) {
402                 incremental_request = CmdlineOption::Disable;
403             }
404         }
405     }
406 
407     if (incremental_request == CmdlineOption::Enable) {
408         // explicitly requested - no fallback
409         return {INSTALL_INCREMENTAL, std::nullopt};
410     }
411     const auto bestMode = best_install_mode();
412     if (incremental_request == CmdlineOption::None) {
413         // no opinion - use incremental, fallback to regular on a failure.
414         return {INSTALL_INCREMENTAL, bestMode};
415     }
416     // incremental turned off - use the regular best mode without a fallback.
417     return {bestMode, std::nullopt};
418 }
419 
parse_install_mode(std::vector<const char * > argv,InstallMode * install_mode,CmdlineOption * incremental_request,bool * incremental_wait)420 static std::vector<const char*> parse_install_mode(std::vector<const char*> argv,
421                                                    InstallMode* install_mode,
422                                                    CmdlineOption* incremental_request,
423                                                    bool* incremental_wait) {
424     *install_mode = INSTALL_DEFAULT;
425     *incremental_request = CmdlineOption::None;
426     *incremental_wait = false;
427 
428     std::vector<const char*> passthrough;
429     for (auto&& arg : argv) {
430         if (arg == "--streaming"sv) {
431             *install_mode = INSTALL_STREAM;
432         } else if (arg == "--no-streaming"sv) {
433             *install_mode = INSTALL_PUSH;
434         } else if (strlen(arg) >= "--incr"sv.size() && "--incremental"sv.starts_with(arg)) {
435             *incremental_request = CmdlineOption::Enable;
436         } else if (strlen(arg) >= "--no-incr"sv.size() && "--no-incremental"sv.starts_with(arg)) {
437             *incremental_request = CmdlineOption::Disable;
438         } else if (arg == "--wait"sv) {
439             *incremental_wait = true;
440         } else {
441             passthrough.push_back(arg);
442         }
443     }
444     return passthrough;
445 }
446 
parse_fast_deploy_mode(std::vector<const char * > argv,bool * use_fastdeploy,FastDeploy_AgentUpdateStrategy * agent_update_strategy)447 static std::vector<const char*> parse_fast_deploy_mode(
448         std::vector<const char*> argv, bool* use_fastdeploy,
449         FastDeploy_AgentUpdateStrategy* agent_update_strategy) {
450     *use_fastdeploy = false;
451     *agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
452 
453     std::vector<const char*> passthrough;
454     for (auto&& arg : argv) {
455         if (arg == "--fastdeploy"sv) {
456             *use_fastdeploy = true;
457         } else if (arg == "--no-fastdeploy"sv) {
458             *use_fastdeploy = false;
459         } else if (arg == "--force-agent"sv) {
460             *agent_update_strategy = FastDeploy_AgentUpdateAlways;
461         } else if (arg == "--date-check-agent"sv) {
462             *agent_update_strategy = FastDeploy_AgentUpdateNewerTimeStamp;
463         } else if (arg == "--version-check-agent"sv) {
464             *agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
465         } else {
466             passthrough.push_back(arg);
467         }
468     }
469     return passthrough;
470 }
471 
install_app(int argc,const char ** argv)472 int install_app(int argc, const char** argv) {
473     InstallMode install_mode = INSTALL_DEFAULT;
474     auto incremental_request = CmdlineOption::None;
475     bool incremental_wait = false;
476 
477     bool use_fastdeploy = false;
478     FastDeploy_AgentUpdateStrategy agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
479 
480     auto unused_argv = parse_install_mode({argv, argv + argc}, &install_mode, &incremental_request,
481                                           &incremental_wait);
482     auto passthrough_argv =
483             parse_fast_deploy_mode(std::move(unused_argv), &use_fastdeploy, &agent_update_strategy);
484 
485     auto [primary_mode, fallback_mode] =
486             calculate_install_mode(install_mode, use_fastdeploy, incremental_request);
487     if ((primary_mode == INSTALL_STREAM ||
488          fallback_mode.value_or(INSTALL_PUSH) == INSTALL_STREAM) &&
489         best_install_mode() == INSTALL_PUSH) {
490         error_exit("Attempting to use streaming install on unsupported device");
491     }
492 
493     if (use_fastdeploy && get_device_api_level() < kFastDeployMinApi) {
494         fprintf(stderr,
495                 "Fast Deploy is only compatible with devices of API version %d or higher, "
496                 "ignoring.\n",
497                 kFastDeployMinApi);
498         use_fastdeploy = false;
499     }
500     fastdeploy_set_agent_update_strategy(agent_update_strategy);
501 
502     if (passthrough_argv.size() < 2) {
503         error_exit("install requires an apk argument");
504     }
505 
506     auto run_install_mode = [&](InstallMode install_mode, bool silent) {
507         switch (install_mode) {
508             case INSTALL_PUSH:
509                 return install_app_legacy(passthrough_argv.size(), passthrough_argv.data(),
510                                           use_fastdeploy);
511             case INSTALL_STREAM:
512                 return install_app_streamed(passthrough_argv.size(), passthrough_argv.data(),
513                                             use_fastdeploy);
514             case INSTALL_INCREMENTAL:
515                 return install_app_incremental(passthrough_argv.size(), passthrough_argv.data(),
516                                                incremental_wait, silent);
517             case INSTALL_DEFAULT:
518             default:
519                 error_exit("invalid install mode");
520         }
521     };
522     auto res = run_install_mode(primary_mode, fallback_mode.has_value());
523     if (res && fallback_mode.value_or(primary_mode) != primary_mode) {
524         res = run_install_mode(*fallback_mode, false);
525     }
526     return res;
527 }
528 
install_multiple_app_streamed(int argc,const char ** argv)529 static int install_multiple_app_streamed(int argc, const char** argv) {
530     // Find all APK arguments starting at end.
531     // All other arguments passed through verbatim.
532     int first_apk = -1;
533     uint64_t total_size = 0;
534     for (int i = argc - 1; i >= 0; i--) {
535         const char* file = argv[i];
536         if (android::base::EndsWithIgnoreCase(argv[i], ".apex")) {
537             error_exit("APEX packages are not compatible with install-multiple");
538         }
539 
540         if (android::base::EndsWithIgnoreCase(file, ".apk") ||
541             android::base::EndsWithIgnoreCase(
542                     file, ".dm") ||  // dex metadata, for cloud profile and cloud verification
543             android::base::EndsWithIgnoreCase(
544                     file, ".sdm") ||  // secure dex metadata, for cloud compilation
545             android::base::EndsWithIgnoreCase(file, ".fsv_sig") ||
546             android::base::EndsWithIgnoreCase(file, ".idsig")) {  // v4 external signature
547             struct stat sb;
548             if (stat(file, &sb) == -1) perror_exit("failed to stat \"%s\"", file);
549             total_size += sb.st_size;
550             first_apk = i;
551         } else {
552             break;
553         }
554     }
555 
556     if (first_apk == -1) error_exit("need APK file on command line");
557 
558     const bool use_abb_exec = is_abb_exec_supported();
559     const std::string install_cmd =
560             use_abb_exec ? "package"
561                          : best_install_mode() == INSTALL_PUSH ? "exec:pm" : "exec:cmd package";
562 
563     std::vector<std::string> cmd_args = {install_cmd, "install-create", "-S",
564                                          std::to_string(total_size)};
565     cmd_args.reserve(first_apk + 4);
566     for (int i = 0; i < first_apk; i++) {
567         if (use_abb_exec) {
568             cmd_args.push_back(argv[i]);
569         } else {
570             cmd_args.push_back(escape_arg(argv[i]));
571         }
572     }
573 
574     // Create install session
575     std::string error;
576     char buf[BUFSIZ];
577     {
578         unique_fd fd = send_command(cmd_args, &error);
579         if (fd < 0) {
580             perror_exit("connect error for create: %s", error.c_str());
581         }
582         read_status_line(fd.get(), buf, sizeof(buf));
583     }
584 
585     int session_id = -1;
586     if (!strncmp("Success", buf, 7)) {
587         char* start = strrchr(buf, '[');
588         char* end = strrchr(buf, ']');
589         if (start && end) {
590             *end = '\0';
591             session_id = strtol(start + 1, nullptr, 10);
592         }
593     }
594     if (session_id < 0) {
595         fprintf(stderr, "adb: failed to create session\n");
596         fputs(buf, stderr);
597         return EXIT_FAILURE;
598     }
599     const auto session_id_str = std::to_string(session_id);
600 
601     // Valid session, now stream the APKs
602     bool success = true;
603     for (int i = first_apk; i < argc; i++) {
604         const char* file = argv[i];
605         struct stat sb;
606         if (stat(file, &sb) == -1) {
607             fprintf(stderr, "adb: failed to stat \"%s\": %s\n", file, strerror(errno));
608             success = false;
609             goto finalize_session;
610         }
611 
612         std::vector<std::string> cmd_args = {
613                 install_cmd,
614                 "install-write",
615                 "-S",
616                 std::to_string(sb.st_size),
617                 session_id_str,
618                 android::base::Basename(file),
619                 "-",
620         };
621 
622         unique_fd local_fd(adb_open(file, O_RDONLY | O_CLOEXEC));
623         if (local_fd < 0) {
624             fprintf(stderr, "adb: failed to open \"%s\": %s\n", file, strerror(errno));
625             success = false;
626             goto finalize_session;
627         }
628 
629         std::string error;
630         unique_fd remote_fd = send_command(cmd_args, &error);
631         if (remote_fd < 0) {
632             fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
633             success = false;
634             goto finalize_session;
635         }
636 
637         if (!copy_to_file(local_fd.get(), remote_fd.get())) {
638             fprintf(stderr, "adb: failed to write \"%s\": %s\n", file, strerror(errno));
639             success = false;
640             goto finalize_session;
641         }
642 
643         read_status_line(remote_fd.get(), buf, sizeof(buf));
644 
645         if (strncmp("Success", buf, 7)) {
646             fprintf(stderr, "adb: failed to write \"%s\"\n", file);
647             fputs(buf, stderr);
648             success = false;
649             goto finalize_session;
650         }
651     }
652 
653 finalize_session:
654     // Commit session if we streamed everything okay; otherwise abandon.
655     std::vector<std::string> service_args = {
656             install_cmd,
657             success ? "install-commit" : "install-abandon",
658             session_id_str,
659     };
660     {
661         unique_fd fd = send_command(service_args, &error);
662         if (fd < 0) {
663             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
664             return EXIT_FAILURE;
665         }
666         read_status_line(fd.get(), buf, sizeof(buf));
667     }
668     if (!success) return EXIT_FAILURE;
669 
670     if (strncmp("Success", buf, 7)) {
671         fprintf(stderr, "adb: failed to finalize session\n");
672         fputs(buf, stderr);
673         return EXIT_FAILURE;
674     }
675 
676     fputs(buf, stdout);
677     return EXIT_SUCCESS;
678 }
679 
install_multiple_app(int argc,const char ** argv)680 int install_multiple_app(int argc, const char** argv) {
681     InstallMode install_mode = INSTALL_DEFAULT;
682     auto incremental_request = CmdlineOption::None;
683     bool incremental_wait = false;
684     bool use_fastdeploy = false;
685 
686     auto passthrough_argv = parse_install_mode({argv + 1, argv + argc}, &install_mode,
687                                                &incremental_request, &incremental_wait);
688 
689     auto [primary_mode, fallback_mode] =
690             calculate_install_mode(install_mode, use_fastdeploy, incremental_request);
691     if ((primary_mode == INSTALL_STREAM ||
692          fallback_mode.value_or(INSTALL_PUSH) == INSTALL_STREAM) &&
693         best_install_mode() == INSTALL_PUSH) {
694         error_exit("Attempting to use streaming install on unsupported device");
695     }
696 
697     auto run_install_mode = [&](InstallMode install_mode, bool silent) {
698         switch (install_mode) {
699             case INSTALL_PUSH:
700             case INSTALL_STREAM:
701                 return install_multiple_app_streamed(passthrough_argv.size(),
702                                                      passthrough_argv.data());
703             case INSTALL_INCREMENTAL:
704                 return install_app_incremental(passthrough_argv.size(), passthrough_argv.data(),
705                                                incremental_wait, silent);
706             case INSTALL_DEFAULT:
707             default:
708                 error_exit("invalid install mode");
709         }
710     };
711     auto res = run_install_mode(primary_mode, fallback_mode.has_value());
712     if (res && fallback_mode.value_or(primary_mode) != primary_mode) {
713         res = run_install_mode(*fallback_mode, false);
714     }
715     return res;
716 }
717 
install_multi_package(int argc,const char ** argv)718 int install_multi_package(int argc, const char** argv) {
719     // Find all APK arguments starting at end.
720     // All other arguments passed through verbatim.
721     bool apex_found = false;
722     int first_package = -1;
723     for (int i = argc - 1; i >= 0; i--) {
724         const char* file = argv[i];
725         if (android::base::EndsWithIgnoreCase(file, ".apk") ||
726             android::base::EndsWithIgnoreCase(file, ".apex")) {
727             first_package = i;
728             if (android::base::EndsWithIgnoreCase(file, ".apex")) {
729                 apex_found = true;
730             }
731         } else {
732             break;
733         }
734     }
735 
736     if (first_package == -1) error_exit("need APK or APEX files on command line");
737 
738     if (best_install_mode() == INSTALL_PUSH) {
739         fprintf(stderr, "adb: multi-package install is not supported on this device\n");
740         return EXIT_FAILURE;
741     }
742 
743     const bool use_abb_exec = is_abb_exec_supported();
744     const std::string install_cmd = use_abb_exec ? "package" : "exec:cmd package";
745 
746     std::vector<std::string> multi_package_cmd_args = {install_cmd, "install-create",
747                                                        "--multi-package"};
748 
749     multi_package_cmd_args.reserve(first_package + 4);
750     for (int i = 1; i < first_package; i++) {
751         if (use_abb_exec) {
752             multi_package_cmd_args.push_back(argv[i]);
753         } else {
754             multi_package_cmd_args.push_back(escape_arg(argv[i]));
755         }
756     }
757 
758     if (apex_found) {
759         multi_package_cmd_args.emplace_back("--staged");
760     }
761 
762     // Create multi-package install session
763     std::string error;
764     char buf[BUFSIZ];
765     {
766         unique_fd fd = send_command(multi_package_cmd_args, &error);
767         if (fd < 0) {
768             fprintf(stderr, "adb: connect error for create multi-package: %s\n", error.c_str());
769             return EXIT_FAILURE;
770         }
771         read_status_line(fd.get(), buf, sizeof(buf));
772     }
773 
774     int parent_session_id = -1;
775     if (!strncmp("Success", buf, 7)) {
776         char* start = strrchr(buf, '[');
777         char* end = strrchr(buf, ']');
778         if (start && end) {
779             *end = '\0';
780             parent_session_id = strtol(start + 1, nullptr, 10);
781         }
782     }
783     if (parent_session_id < 0) {
784         fprintf(stderr, "adb: failed to create multi-package session\n");
785         fputs(buf, stderr);
786         return EXIT_FAILURE;
787     }
788     const auto parent_session_id_str = std::to_string(parent_session_id);
789 
790     fprintf(stdout, "Created parent session ID %d.\n", parent_session_id);
791 
792     std::vector<int> session_ids;
793 
794     // Valid session, now create the individual sessions and stream the APKs
795     int success = EXIT_FAILURE;
796     std::vector<std::string> individual_cmd_args = {install_cmd, "install-create"};
797     for (int i = 1; i < first_package; i++) {
798         if (use_abb_exec) {
799             individual_cmd_args.push_back(argv[i]);
800         } else {
801             individual_cmd_args.push_back(escape_arg(argv[i]));
802         }
803     }
804     if (apex_found) {
805         individual_cmd_args.emplace_back("--staged");
806     }
807 
808     std::vector<std::string> individual_apex_cmd_args;
809     if (apex_found) {
810         individual_apex_cmd_args = individual_cmd_args;
811         individual_apex_cmd_args.emplace_back("--apex");
812     }
813 
814     std::vector<std::string> add_session_cmd_args = {
815             install_cmd,
816             "install-add-session",
817             parent_session_id_str,
818     };
819 
820     for (int i = first_package; i < argc; i++) {
821         const char* file = argv[i];
822         char buf[BUFSIZ];
823         {
824             unique_fd fd;
825             // Create individual install session
826             if (android::base::EndsWithIgnoreCase(file, ".apex")) {
827                 fd = send_command(individual_apex_cmd_args, &error);
828             } else {
829                 fd = send_command(individual_cmd_args, &error);
830             }
831             if (fd < 0) {
832                 fprintf(stderr, "adb: connect error for create: %s\n", error.c_str());
833                 goto finalize_multi_package_session;
834             }
835             read_status_line(fd.get(), buf, sizeof(buf));
836         }
837 
838         int session_id = -1;
839         if (!strncmp("Success", buf, 7)) {
840             char* start = strrchr(buf, '[');
841             char* end = strrchr(buf, ']');
842             if (start && end) {
843                 *end = '\0';
844                 session_id = strtol(start + 1, nullptr, 10);
845             }
846         }
847         if (session_id < 0) {
848             fprintf(stderr, "adb: failed to create multi-package session\n");
849             fputs(buf, stderr);
850             goto finalize_multi_package_session;
851         }
852         const auto session_id_str = std::to_string(session_id);
853 
854         fprintf(stdout, "Created child session ID %d.\n", session_id);
855         session_ids.push_back(session_id);
856 
857         // Support splitAPKs by allowing the notation split1.apk:split2.apk:split3.apk as argument.
858         // The character used as separator is OS-dependent, see ENV_PATH_SEPARATOR_STR.
859         std::vector<std::string> splits = android::base::Split(file, ENV_PATH_SEPARATOR_STR);
860 
861         for (const std::string& split : splits) {
862             struct stat sb;
863             if (stat(split.c_str(), &sb) == -1) {
864                 fprintf(stderr, "adb: failed to stat %s: %s\n", split.c_str(), strerror(errno));
865                 goto finalize_multi_package_session;
866             }
867 
868             std::vector<std::string> cmd_args = {
869                     install_cmd,
870                     "install-write",
871                     "-S",
872                     std::to_string(sb.st_size),
873                     session_id_str,
874                     android::base::StringPrintf("%d_%s", i, android::base::Basename(split).c_str()),
875                     "-",
876             };
877 
878             unique_fd local_fd(adb_open(split.c_str(), O_RDONLY | O_CLOEXEC));
879             if (local_fd < 0) {
880                 fprintf(stderr, "adb: failed to open %s: %s\n", split.c_str(), strerror(errno));
881                 goto finalize_multi_package_session;
882             }
883 
884             std::string error;
885             unique_fd remote_fd = send_command(cmd_args, &error);
886             if (remote_fd < 0) {
887                 fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
888                 goto finalize_multi_package_session;
889             }
890 
891             if (!copy_to_file(local_fd.get(), remote_fd.get())) {
892                 fprintf(stderr, "adb: failed to write %s: %s\n", split.c_str(), strerror(errno));
893                 goto finalize_multi_package_session;
894             }
895 
896             read_status_line(remote_fd.get(), buf, sizeof(buf));
897 
898             if (strncmp("Success", buf, 7)) {
899                 fprintf(stderr, "adb: failed to write %s\n", split.c_str());
900                 fputs(buf, stderr);
901                 goto finalize_multi_package_session;
902             }
903         }
904         add_session_cmd_args.push_back(std::to_string(session_id));
905     }
906 
907     {
908         unique_fd fd = send_command(add_session_cmd_args, &error);
909         if (fd < 0) {
910             fprintf(stderr, "adb: connect error for install-add-session: %s\n", error.c_str());
911             goto finalize_multi_package_session;
912         }
913         read_status_line(fd.get(), buf, sizeof(buf));
914     }
915 
916     if (strncmp("Success", buf, 7)) {
917         fprintf(stderr, "adb: failed to link sessions (%s)\n",
918                 android::base::Join(add_session_cmd_args, " ").c_str());
919         fputs(buf, stderr);
920         goto finalize_multi_package_session;
921     }
922 
923     // no failures means we can proceed with the assumption of success
924     success = 0;
925 
926 finalize_multi_package_session:
927     // Commit session if we streamed everything okay; otherwise abandon
928     std::vector<std::string> service_args;
929     if (success == 0) {
930         service_args.push_back(install_cmd);
931         service_args.push_back("install-commit");
932         // If successful, we need to forward args to install-commit
933         for (int i = 1; i < first_package - 1; i++) {
934             if (strcmp(argv[i], "--staged-ready-timeout") == 0) {
935                 service_args.push_back(argv[i]);
936                 service_args.push_back(argv[i + 1]);
937                 i++;
938             }
939         }
940         service_args.push_back(parent_session_id_str);
941     } else {
942         service_args = {install_cmd, "install-abandon", parent_session_id_str};
943     }
944 
945     {
946         unique_fd fd = send_command(service_args, &error);
947         if (fd < 0) {
948             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
949             return EXIT_FAILURE;
950         }
951         read_status_line(fd.get(), buf, sizeof(buf));
952     }
953 
954     if (!strncmp("Success", buf, 7)) {
955         fputs(buf, stdout);
956         if (success == 0) {
957             return 0;
958         }
959     } else {
960         fprintf(stderr, "adb: failed to finalize session\n");
961         fputs(buf, stderr);
962     }
963 
964     session_ids.push_back(parent_session_id);
965     // try to abandon all remaining sessions
966     for (std::size_t i = 0; i < session_ids.size(); i++) {
967         std::vector<std::string> service_args = {
968                 install_cmd,
969                 "install-abandon",
970                 std::to_string(session_ids[i]),
971         };
972         fprintf(stderr, "Attempting to abandon session ID %d\n", session_ids[i]);
973         unique_fd fd = send_command(service_args, &error);
974         if (fd < 0) {
975             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
976             continue;
977         }
978         read_status_line(fd.get(), buf, sizeof(buf));
979     }
980     return EXIT_FAILURE;
981 }
982 
delete_device_file(const std::string & filename)983 int delete_device_file(const std::string& filename) {
984     // http://b/17339227 "Sideloading a Readonly File Results in a Prompt to
985     // Delete" caused us to add `-f` here, to avoid the equivalent of the `-i`
986     // prompt that you get from BSD rm (used in Android 5) if you have a
987     // non-writable file and stdin is a tty (which is true for old versions of
988     // adbd).
989     //
990     // Unfortunately, `rm -f` requires Android 4.3, so that workaround broke
991     // earlier Android releases. This was reported as http://b/37704384 "adb
992     // install -r passes invalid argument to rm on Android 4.1" and
993     // http://b/37035817 "ADB Fails: rm failed for -f, No such file or
994     // directory".
995     //
996     // Testing on a variety of devices and emulators shows that redirecting
997     // stdin is sufficient to avoid the pseudo-`-i`, and works on toolbox,
998     // BSD, and toybox versions of rm.
999     return send_shell_command("rm " + escape_arg(filename) + " </dev/null");
1000 }
1001