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