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(file, ".dm") ||
542             android::base::EndsWithIgnoreCase(file, ".fsv_sig") ||
543             android::base::EndsWithIgnoreCase(file, ".idsig")) {  // v4 external signature.
544             struct stat sb;
545             if (stat(file, &sb) == -1) perror_exit("failed to stat \"%s\"", file);
546             total_size += sb.st_size;
547             first_apk = i;
548         } else {
549             break;
550         }
551     }
552 
553     if (first_apk == -1) error_exit("need APK file on command line");
554 
555     const bool use_abb_exec = is_abb_exec_supported();
556     const std::string install_cmd =
557             use_abb_exec ? "package"
558                          : best_install_mode() == INSTALL_PUSH ? "exec:pm" : "exec:cmd package";
559 
560     std::vector<std::string> cmd_args = {install_cmd, "install-create", "-S",
561                                          std::to_string(total_size)};
562     cmd_args.reserve(first_apk + 4);
563     for (int i = 0; i < first_apk; i++) {
564         if (use_abb_exec) {
565             cmd_args.push_back(argv[i]);
566         } else {
567             cmd_args.push_back(escape_arg(argv[i]));
568         }
569     }
570 
571     // Create install session
572     std::string error;
573     char buf[BUFSIZ];
574     {
575         unique_fd fd = send_command(cmd_args, &error);
576         if (fd < 0) {
577             perror_exit("connect error for create: %s", error.c_str());
578         }
579         read_status_line(fd.get(), buf, sizeof(buf));
580     }
581 
582     int session_id = -1;
583     if (!strncmp("Success", buf, 7)) {
584         char* start = strrchr(buf, '[');
585         char* end = strrchr(buf, ']');
586         if (start && end) {
587             *end = '\0';
588             session_id = strtol(start + 1, nullptr, 10);
589         }
590     }
591     if (session_id < 0) {
592         fprintf(stderr, "adb: failed to create session\n");
593         fputs(buf, stderr);
594         return EXIT_FAILURE;
595     }
596     const auto session_id_str = std::to_string(session_id);
597 
598     // Valid session, now stream the APKs
599     bool success = true;
600     for (int i = first_apk; i < argc; i++) {
601         const char* file = argv[i];
602         struct stat sb;
603         if (stat(file, &sb) == -1) {
604             fprintf(stderr, "adb: failed to stat \"%s\": %s\n", file, strerror(errno));
605             success = false;
606             goto finalize_session;
607         }
608 
609         std::vector<std::string> cmd_args = {
610                 install_cmd,
611                 "install-write",
612                 "-S",
613                 std::to_string(sb.st_size),
614                 session_id_str,
615                 android::base::Basename(file),
616                 "-",
617         };
618 
619         unique_fd local_fd(adb_open(file, O_RDONLY | O_CLOEXEC));
620         if (local_fd < 0) {
621             fprintf(stderr, "adb: failed to open \"%s\": %s\n", file, strerror(errno));
622             success = false;
623             goto finalize_session;
624         }
625 
626         std::string error;
627         unique_fd remote_fd = send_command(cmd_args, &error);
628         if (remote_fd < 0) {
629             fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
630             success = false;
631             goto finalize_session;
632         }
633 
634         if (!copy_to_file(local_fd.get(), remote_fd.get())) {
635             fprintf(stderr, "adb: failed to write \"%s\": %s\n", file, strerror(errno));
636             success = false;
637             goto finalize_session;
638         }
639 
640         read_status_line(remote_fd.get(), buf, sizeof(buf));
641 
642         if (strncmp("Success", buf, 7)) {
643             fprintf(stderr, "adb: failed to write \"%s\"\n", file);
644             fputs(buf, stderr);
645             success = false;
646             goto finalize_session;
647         }
648     }
649 
650 finalize_session:
651     // Commit session if we streamed everything okay; otherwise abandon.
652     std::vector<std::string> service_args = {
653             install_cmd,
654             success ? "install-commit" : "install-abandon",
655             session_id_str,
656     };
657     {
658         unique_fd fd = send_command(service_args, &error);
659         if (fd < 0) {
660             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
661             return EXIT_FAILURE;
662         }
663         read_status_line(fd.get(), buf, sizeof(buf));
664     }
665     if (!success) return EXIT_FAILURE;
666 
667     if (strncmp("Success", buf, 7)) {
668         fprintf(stderr, "adb: failed to finalize session\n");
669         fputs(buf, stderr);
670         return EXIT_FAILURE;
671     }
672 
673     fputs(buf, stdout);
674     return EXIT_SUCCESS;
675 }
676 
install_multiple_app(int argc,const char ** argv)677 int install_multiple_app(int argc, const char** argv) {
678     InstallMode install_mode = INSTALL_DEFAULT;
679     auto incremental_request = CmdlineOption::None;
680     bool incremental_wait = false;
681     bool use_fastdeploy = false;
682 
683     auto passthrough_argv = parse_install_mode({argv + 1, argv + argc}, &install_mode,
684                                                &incremental_request, &incremental_wait);
685 
686     auto [primary_mode, fallback_mode] =
687             calculate_install_mode(install_mode, use_fastdeploy, incremental_request);
688     if ((primary_mode == INSTALL_STREAM ||
689          fallback_mode.value_or(INSTALL_PUSH) == INSTALL_STREAM) &&
690         best_install_mode() == INSTALL_PUSH) {
691         error_exit("Attempting to use streaming install on unsupported device");
692     }
693 
694     auto run_install_mode = [&](InstallMode install_mode, bool silent) {
695         switch (install_mode) {
696             case INSTALL_PUSH:
697             case INSTALL_STREAM:
698                 return install_multiple_app_streamed(passthrough_argv.size(),
699                                                      passthrough_argv.data());
700             case INSTALL_INCREMENTAL:
701                 return install_app_incremental(passthrough_argv.size(), passthrough_argv.data(),
702                                                incremental_wait, silent);
703             case INSTALL_DEFAULT:
704             default:
705                 error_exit("invalid install mode");
706         }
707     };
708     auto res = run_install_mode(primary_mode, fallback_mode.has_value());
709     if (res && fallback_mode.value_or(primary_mode) != primary_mode) {
710         res = run_install_mode(*fallback_mode, false);
711     }
712     return res;
713 }
714 
install_multi_package(int argc,const char ** argv)715 int install_multi_package(int argc, const char** argv) {
716     // Find all APK arguments starting at end.
717     // All other arguments passed through verbatim.
718     bool apex_found = false;
719     int first_package = -1;
720     for (int i = argc - 1; i >= 0; i--) {
721         const char* file = argv[i];
722         if (android::base::EndsWithIgnoreCase(file, ".apk") ||
723             android::base::EndsWithIgnoreCase(file, ".apex")) {
724             first_package = i;
725             if (android::base::EndsWithIgnoreCase(file, ".apex")) {
726                 apex_found = true;
727             }
728         } else {
729             break;
730         }
731     }
732 
733     if (first_package == -1) error_exit("need APK or APEX files on command line");
734 
735     if (best_install_mode() == INSTALL_PUSH) {
736         fprintf(stderr, "adb: multi-package install is not supported on this device\n");
737         return EXIT_FAILURE;
738     }
739 
740     const bool use_abb_exec = is_abb_exec_supported();
741     const std::string install_cmd = use_abb_exec ? "package" : "exec:cmd package";
742 
743     std::vector<std::string> multi_package_cmd_args = {install_cmd, "install-create",
744                                                        "--multi-package"};
745 
746     multi_package_cmd_args.reserve(first_package + 4);
747     for (int i = 1; i < first_package; i++) {
748         if (use_abb_exec) {
749             multi_package_cmd_args.push_back(argv[i]);
750         } else {
751             multi_package_cmd_args.push_back(escape_arg(argv[i]));
752         }
753     }
754 
755     if (apex_found) {
756         multi_package_cmd_args.emplace_back("--staged");
757     }
758 
759     // Create multi-package install session
760     std::string error;
761     char buf[BUFSIZ];
762     {
763         unique_fd fd = send_command(multi_package_cmd_args, &error);
764         if (fd < 0) {
765             fprintf(stderr, "adb: connect error for create multi-package: %s\n", error.c_str());
766             return EXIT_FAILURE;
767         }
768         read_status_line(fd.get(), buf, sizeof(buf));
769     }
770 
771     int parent_session_id = -1;
772     if (!strncmp("Success", buf, 7)) {
773         char* start = strrchr(buf, '[');
774         char* end = strrchr(buf, ']');
775         if (start && end) {
776             *end = '\0';
777             parent_session_id = strtol(start + 1, nullptr, 10);
778         }
779     }
780     if (parent_session_id < 0) {
781         fprintf(stderr, "adb: failed to create multi-package session\n");
782         fputs(buf, stderr);
783         return EXIT_FAILURE;
784     }
785     const auto parent_session_id_str = std::to_string(parent_session_id);
786 
787     fprintf(stdout, "Created parent session ID %d.\n", parent_session_id);
788 
789     std::vector<int> session_ids;
790 
791     // Valid session, now create the individual sessions and stream the APKs
792     int success = EXIT_FAILURE;
793     std::vector<std::string> individual_cmd_args = {install_cmd, "install-create"};
794     for (int i = 1; i < first_package; i++) {
795         if (use_abb_exec) {
796             individual_cmd_args.push_back(argv[i]);
797         } else {
798             individual_cmd_args.push_back(escape_arg(argv[i]));
799         }
800     }
801     if (apex_found) {
802         individual_cmd_args.emplace_back("--staged");
803     }
804 
805     std::vector<std::string> individual_apex_cmd_args;
806     if (apex_found) {
807         individual_apex_cmd_args = individual_cmd_args;
808         individual_apex_cmd_args.emplace_back("--apex");
809     }
810 
811     std::vector<std::string> add_session_cmd_args = {
812             install_cmd,
813             "install-add-session",
814             parent_session_id_str,
815     };
816 
817     for (int i = first_package; i < argc; i++) {
818         const char* file = argv[i];
819         char buf[BUFSIZ];
820         {
821             unique_fd fd;
822             // Create individual install session
823             if (android::base::EndsWithIgnoreCase(file, ".apex")) {
824                 fd = send_command(individual_apex_cmd_args, &error);
825             } else {
826                 fd = send_command(individual_cmd_args, &error);
827             }
828             if (fd < 0) {
829                 fprintf(stderr, "adb: connect error for create: %s\n", error.c_str());
830                 goto finalize_multi_package_session;
831             }
832             read_status_line(fd.get(), buf, sizeof(buf));
833         }
834 
835         int session_id = -1;
836         if (!strncmp("Success", buf, 7)) {
837             char* start = strrchr(buf, '[');
838             char* end = strrchr(buf, ']');
839             if (start && end) {
840                 *end = '\0';
841                 session_id = strtol(start + 1, nullptr, 10);
842             }
843         }
844         if (session_id < 0) {
845             fprintf(stderr, "adb: failed to create multi-package session\n");
846             fputs(buf, stderr);
847             goto finalize_multi_package_session;
848         }
849         const auto session_id_str = std::to_string(session_id);
850 
851         fprintf(stdout, "Created child session ID %d.\n", session_id);
852         session_ids.push_back(session_id);
853 
854         // Support splitAPKs by allowing the notation split1.apk:split2.apk:split3.apk as argument.
855         // The character used as separator is OS-dependent, see ENV_PATH_SEPARATOR_STR.
856         std::vector<std::string> splits = android::base::Split(file, ENV_PATH_SEPARATOR_STR);
857 
858         for (const std::string& split : splits) {
859             struct stat sb;
860             if (stat(split.c_str(), &sb) == -1) {
861                 fprintf(stderr, "adb: failed to stat %s: %s\n", split.c_str(), strerror(errno));
862                 goto finalize_multi_package_session;
863             }
864 
865             std::vector<std::string> cmd_args = {
866                     install_cmd,
867                     "install-write",
868                     "-S",
869                     std::to_string(sb.st_size),
870                     session_id_str,
871                     android::base::StringPrintf("%d_%s", i, android::base::Basename(split).c_str()),
872                     "-",
873             };
874 
875             unique_fd local_fd(adb_open(split.c_str(), O_RDONLY | O_CLOEXEC));
876             if (local_fd < 0) {
877                 fprintf(stderr, "adb: failed to open %s: %s\n", split.c_str(), strerror(errno));
878                 goto finalize_multi_package_session;
879             }
880 
881             std::string error;
882             unique_fd remote_fd = send_command(cmd_args, &error);
883             if (remote_fd < 0) {
884                 fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
885                 goto finalize_multi_package_session;
886             }
887 
888             if (!copy_to_file(local_fd.get(), remote_fd.get())) {
889                 fprintf(stderr, "adb: failed to write %s: %s\n", split.c_str(), strerror(errno));
890                 goto finalize_multi_package_session;
891             }
892 
893             read_status_line(remote_fd.get(), buf, sizeof(buf));
894 
895             if (strncmp("Success", buf, 7)) {
896                 fprintf(stderr, "adb: failed to write %s\n", split.c_str());
897                 fputs(buf, stderr);
898                 goto finalize_multi_package_session;
899             }
900         }
901         add_session_cmd_args.push_back(std::to_string(session_id));
902     }
903 
904     {
905         unique_fd fd = send_command(add_session_cmd_args, &error);
906         if (fd < 0) {
907             fprintf(stderr, "adb: connect error for install-add-session: %s\n", error.c_str());
908             goto finalize_multi_package_session;
909         }
910         read_status_line(fd.get(), buf, sizeof(buf));
911     }
912 
913     if (strncmp("Success", buf, 7)) {
914         fprintf(stderr, "adb: failed to link sessions (%s)\n",
915                 android::base::Join(add_session_cmd_args, " ").c_str());
916         fputs(buf, stderr);
917         goto finalize_multi_package_session;
918     }
919 
920     // no failures means we can proceed with the assumption of success
921     success = 0;
922 
923 finalize_multi_package_session:
924     // Commit session if we streamed everything okay; otherwise abandon
925     std::vector<std::string> service_args;
926     if (success == 0) {
927         service_args.push_back(install_cmd);
928         service_args.push_back("install-commit");
929         // If successful, we need to forward args to install-commit
930         for (int i = 1; i < first_package - 1; i++) {
931             if (strcmp(argv[i], "--staged-ready-timeout") == 0) {
932                 service_args.push_back(argv[i]);
933                 service_args.push_back(argv[i + 1]);
934                 i++;
935             }
936         }
937         service_args.push_back(parent_session_id_str);
938     } else {
939         service_args = {install_cmd, "install-abandon", parent_session_id_str};
940     }
941 
942     {
943         unique_fd fd = send_command(service_args, &error);
944         if (fd < 0) {
945             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
946             return EXIT_FAILURE;
947         }
948         read_status_line(fd.get(), buf, sizeof(buf));
949     }
950 
951     if (!strncmp("Success", buf, 7)) {
952         fputs(buf, stdout);
953         if (success == 0) {
954             return 0;
955         }
956     } else {
957         fprintf(stderr, "adb: failed to finalize session\n");
958         fputs(buf, stderr);
959     }
960 
961     session_ids.push_back(parent_session_id);
962     // try to abandon all remaining sessions
963     for (std::size_t i = 0; i < session_ids.size(); i++) {
964         std::vector<std::string> service_args = {
965                 install_cmd,
966                 "install-abandon",
967                 std::to_string(session_ids[i]),
968         };
969         fprintf(stderr, "Attempting to abandon session ID %d\n", session_ids[i]);
970         unique_fd fd = send_command(service_args, &error);
971         if (fd < 0) {
972             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
973             continue;
974         }
975         read_status_line(fd.get(), buf, sizeof(buf));
976     }
977     return EXIT_FAILURE;
978 }
979 
delete_device_file(const std::string & filename)980 int delete_device_file(const std::string& filename) {
981     // http://b/17339227 "Sideloading a Readonly File Results in a Prompt to
982     // Delete" caused us to add `-f` here, to avoid the equivalent of the `-i`
983     // prompt that you get from BSD rm (used in Android 5) if you have a
984     // non-writable file and stdin is a tty (which is true for old versions of
985     // adbd).
986     //
987     // Unfortunately, `rm -f` requires Android 4.3, so that workaround broke
988     // earlier Android releases. This was reported as http://b/37704384 "adb
989     // install -r passes invalid argument to rm on Android 4.1" and
990     // http://b/37035817 "ADB Fails: rm failed for -f, No such file or
991     // directory".
992     //
993     // Testing on a variety of devices and emulators shows that redirecting
994     // stdin is sufficient to avoid the pseudo-`-i`, and works on toolbox,
995     // BSD, and toybox versions of rm.
996     return send_shell_command("rm " + escape_arg(filename) + " </dev/null");
997 }
998