• 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 
43 using namespace std::literals;
44 
45 static constexpr int kFastDeployMinApi = 24;
46 
47 namespace {
48 
49 enum InstallMode {
50     INSTALL_DEFAULT,
51     INSTALL_PUSH,
52     INSTALL_STREAM,
53     INSTALL_INCREMENTAL,
54 };
55 
56 enum class CmdlineOption { None, Enable, Disable };
57 }
58 
best_install_mode()59 static InstallMode best_install_mode() {
60     auto&& features = adb_get_feature_set_or_die();
61     if (CanUseFeature(*features, kFeatureCmd)) {
62         return INSTALL_STREAM;
63     }
64     return INSTALL_PUSH;
65 }
66 
is_apex_supported()67 static bool is_apex_supported() {
68     auto&& features = adb_get_feature_set_or_die();
69     return CanUseFeature(*features, kFeatureApex);
70 }
71 
is_abb_exec_supported()72 static bool is_abb_exec_supported() {
73     auto&& features = adb_get_feature_set_or_die();
74     return CanUseFeature(*features, kFeatureAbbExec);
75 }
76 
pm_command(int argc,const char ** argv)77 static int pm_command(int argc, const char** argv) {
78     std::string cmd = "pm";
79 
80     while (argc-- > 0) {
81         cmd += " " + escape_arg(*argv++);
82     }
83 
84     return send_shell_command(cmd);
85 }
86 
uninstall_app_streamed(int argc,const char ** argv)87 static int uninstall_app_streamed(int argc, const char** argv) {
88     // 'adb uninstall' takes the same arguments as 'cmd package uninstall' on device
89     std::string cmd = "cmd package";
90     while (argc-- > 0) {
91         // deny the '-k' option until the remaining data/cache can be removed with adb/UI
92         if (strcmp(*argv, "-k") == 0) {
93             printf("The -k option uninstalls the application while retaining the "
94                    "data/cache.\n"
95                    "At the moment, there is no way to remove the remaining data.\n"
96                    "You will have to reinstall the application with the same "
97                    "signature, and fully "
98                    "uninstall it.\n"
99                    "If you truly wish to continue, execute 'adb shell cmd package "
100                    "uninstall -k'.\n");
101             return EXIT_FAILURE;
102         }
103         cmd += " " + escape_arg(*argv++);
104     }
105 
106     return send_shell_command(cmd);
107 }
108 
uninstall_app_legacy(int argc,const char ** argv)109 static int uninstall_app_legacy(int argc, const char** argv) {
110     /* if the user choose the -k option, we refuse to do it until devices are
111        out with the option to uninstall the remaining data somehow (adb/ui) */
112     for (int i = 1; i < argc; i++) {
113         if (!strcmp(argv[i], "-k")) {
114             printf("The -k option uninstalls the application while retaining the "
115                    "data/cache.\n"
116                    "At the moment, there is no way to remove the remaining data.\n"
117                    "You will have to reinstall the application with the same "
118                    "signature, and fully "
119                    "uninstall it.\n"
120                    "If you truly wish to continue, execute 'adb shell pm uninstall "
121                    "-k'\n.");
122             return EXIT_FAILURE;
123         }
124     }
125 
126     /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */
127     return pm_command(argc, argv);
128 }
129 
uninstall_app(int argc,const char ** argv)130 int uninstall_app(int argc, const char** argv) {
131     if (best_install_mode() == INSTALL_PUSH) {
132         return uninstall_app_legacy(argc, argv);
133     }
134     return uninstall_app_streamed(argc, argv);
135 }
136 
read_status_line(int fd,char * buf,size_t count)137 static void read_status_line(int fd, char* buf, size_t count) {
138     count--;
139     while (count > 0) {
140         int len = adb_read(fd, buf, count);
141         if (len <= 0) {
142             break;
143         }
144 
145         buf += len;
146         count -= len;
147     }
148     *buf = '\0';
149 }
150 
send_command(const std::vector<std::string> & cmd_args,std::string * error)151 static unique_fd send_command(const std::vector<std::string>& cmd_args, std::string* error) {
152     if (is_abb_exec_supported()) {
153         return send_abb_exec_command(cmd_args, error);
154     } else {
155         return unique_fd(adb_connect(android::base::Join(cmd_args, " "), error));
156     }
157 }
158 
install_app_streamed(int argc,const char ** argv,bool use_fastdeploy)159 static int install_app_streamed(int argc, const char** argv, bool use_fastdeploy) {
160     printf("Performing Streamed Install\n");
161 
162     // The last argument must be the APK file
163     const char* file = argv[argc - 1];
164     if (!android::base::EndsWithIgnoreCase(file, ".apk") &&
165         !android::base::EndsWithIgnoreCase(file, ".apex")) {
166         error_exit("filename doesn't end .apk or .apex: %s", file);
167     }
168 
169     bool is_apex = false;
170     if (android::base::EndsWithIgnoreCase(file, ".apex")) {
171         is_apex = true;
172     }
173     if (is_apex && !is_apex_supported()) {
174         error_exit(".apex is not supported on the target device");
175     }
176 
177     if (is_apex && use_fastdeploy) {
178         error_exit("--fastdeploy doesn't support .apex files");
179     }
180 
181     if (use_fastdeploy) {
182         auto metadata = extract_metadata(file);
183         if (metadata.has_value()) {
184             // pass all but 1st (command) and last (apk path) parameters through to pm for
185             // session creation
186             std::vector<const char*> pm_args{argv + 1, argv + argc - 1};
187             auto patchFd = install_patch(pm_args.size(), pm_args.data());
188             return stream_patch(file, std::move(metadata.value()), std::move(patchFd));
189         }
190     }
191 
192     struct stat sb;
193     if (stat(file, &sb) == -1) {
194         fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
195         return 1;
196     }
197 
198     unique_fd local_fd(adb_open(file, O_RDONLY | O_CLOEXEC));
199     if (local_fd < 0) {
200         fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
201         return 1;
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         fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
234         return 1;
235     }
236 
237     if (!copy_to_file(local_fd.get(), remote_fd.get())) {
238         fprintf(stderr, "adb: failed to install: copy_to_file: %s: %s", file, strerror(errno));
239         return 1;
240     }
241 
242     char buf[BUFSIZ];
243     read_status_line(remote_fd.get(), buf, sizeof(buf));
244     if (strncmp("Success", buf, 7) != 0) {
245         fprintf(stderr, "adb: failed to install %s: %s", file, buf);
246         return 1;
247     }
248 
249     fputs(buf, stdout);
250     return 0;
251 }
252 
install_app_legacy(int argc,const char ** argv,bool use_fastdeploy)253 static int install_app_legacy(int argc, const char** argv, bool use_fastdeploy) {
254     printf("Performing Push Install\n");
255 
256     // Find last APK argument.
257     // All other arguments passed through verbatim.
258     int last_apk = -1;
259     for (int i = argc - 1; i >= 0; i--) {
260         if (android::base::EndsWithIgnoreCase(argv[i], ".apex")) {
261             error_exit("APEX packages are only compatible with Streamed Install");
262         }
263         if (android::base::EndsWithIgnoreCase(argv[i], ".apk")) {
264             last_apk = i;
265             break;
266         }
267     }
268 
269     if (last_apk == -1) error_exit("need APK file on command line");
270 
271     int result = -1;
272     std::vector<const char*> apk_file = {argv[last_apk]};
273     std::string apk_dest = "/data/local/tmp/" + android::base::Basename(argv[last_apk]);
274     argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
275 
276     if (use_fastdeploy) {
277         auto metadata = extract_metadata(apk_file[0]);
278         if (metadata.has_value()) {
279             auto patchFd = apply_patch_on_device(apk_dest.c_str());
280             int status = stream_patch(apk_file[0], std::move(metadata.value()), std::move(patchFd));
281 
282             result = pm_command(argc, argv);
283             delete_device_file(apk_dest);
284 
285             return status;
286         }
287     }
288 
289     if (do_sync_push(apk_file, apk_dest.c_str(), false, CompressionType::Any, false)) {
290         result = pm_command(argc, argv);
291         delete_device_file(apk_dest);
292     }
293 
294     return result;
295 }
296 
297 template <class TimePoint>
ms_between(TimePoint start,TimePoint end)298 static int ms_between(TimePoint start, TimePoint end) {
299     return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
300 }
301 
install_app_incremental(int argc,const char ** argv,bool wait,bool silent)302 static int install_app_incremental(int argc, const char** argv, bool wait, bool silent) {
303     using clock = std::chrono::high_resolution_clock;
304     const auto start = clock::now();
305     int first_apk = -1;
306     int last_apk = -1;
307     incremental::Args passthrough_args = {};
308     for (int i = 0; i < argc; ++i) {
309         const auto arg = std::string_view(argv[i]);
310         if (android::base::EndsWithIgnoreCase(arg, ".apk"sv)) {
311             last_apk = i;
312             if (first_apk == -1) {
313                 first_apk = i;
314             }
315         } else if (arg.starts_with("install"sv)) {
316             // incremental installation command on the device is the same for all its variations in
317             // the adb, e.g. install-multiple or install-multi-package
318         } else {
319             passthrough_args.push_back(arg);
320         }
321     }
322 
323     if (first_apk == -1) {
324         if (!silent) {
325             fprintf(stderr, "error: need at least one APK file on command line\n");
326         }
327         return -1;
328     }
329 
330     auto files = incremental::Files{argv + first_apk, argv + last_apk + 1};
331     if (silent) {
332         // For a silent installation we want to do the lightweight check first and bail early and
333         // quietly if it fails.
334         if (!incremental::can_install(files)) {
335             return -1;
336         }
337     }
338 
339     printf("Performing Incremental Install\n");
340     auto server_process = incremental::install(files, passthrough_args, silent);
341     if (!server_process) {
342         return -1;
343     }
344 
345     const auto end = clock::now();
346     printf("Install command complete in %d ms\n", ms_between(start, end));
347 
348     if (wait) {
349         (*server_process).wait();
350     }
351 
352     return 0;
353 }
354 
calculate_install_mode(InstallMode modeFromArgs,bool fastdeploy,CmdlineOption incremental_request)355 static std::pair<InstallMode, std::optional<InstallMode>> calculate_install_mode(
356         InstallMode modeFromArgs, bool fastdeploy, CmdlineOption incremental_request) {
357     if (incremental_request == CmdlineOption::Enable) {
358         if (fastdeploy) {
359             error_exit(
360                     "--incremental and --fast-deploy options are incompatible. "
361                     "Please choose one");
362         }
363     }
364 
365     if (modeFromArgs != INSTALL_DEFAULT) {
366         if (incremental_request == CmdlineOption::Enable) {
367             error_exit("--incremental is not compatible with other installation modes");
368         }
369         return {modeFromArgs, std::nullopt};
370     }
371 
372     if (incremental_request != CmdlineOption::Disable && !is_abb_exec_supported()) {
373         if (incremental_request == CmdlineOption::None) {
374             incremental_request = CmdlineOption::Disable;
375         } else {
376             error_exit("Device doesn't support incremental installations");
377         }
378     }
379     if (incremental_request == CmdlineOption::None) {
380         // check if the host is ok with incremental by default
381         if (const char* incrementalFromEnv = getenv("ADB_INSTALL_DEFAULT_INCREMENTAL")) {
382             using namespace android::base;
383             auto val = ParseBool(incrementalFromEnv);
384             if (val == ParseBoolResult::kFalse) {
385                 incremental_request = CmdlineOption::Disable;
386             }
387         }
388     }
389     if (incremental_request == CmdlineOption::None) {
390         // still ok: let's see if the device allows using incremental by default
391         // it starts feeling like we're looking for an excuse to not to use incremental...
392         std::string error;
393         std::vector<std::string> args = {"settings", "get",
394                                          "enable_adb_incremental_install_default"};
395         auto fd = send_abb_exec_command(args, &error);
396         if (!fd.ok()) {
397             fprintf(stderr, "adb: retrieving the default device installation mode failed: %s",
398                     error.c_str());
399         } else {
400             char buf[BUFSIZ] = {};
401             read_status_line(fd.get(), buf, sizeof(buf));
402             using namespace android::base;
403             auto val = ParseBool(buf);
404             if (val == ParseBoolResult::kFalse) {
405                 incremental_request = CmdlineOption::Disable;
406             }
407         }
408     }
409 
410     if (incremental_request == CmdlineOption::Enable) {
411         // explicitly requested - no fallback
412         return {INSTALL_INCREMENTAL, std::nullopt};
413     }
414     const auto bestMode = best_install_mode();
415     if (incremental_request == CmdlineOption::None) {
416         // no opinion - use incremental, fallback to regular on a failure.
417         return {INSTALL_INCREMENTAL, bestMode};
418     }
419     // incremental turned off - use the regular best mode without a fallback.
420     return {bestMode, std::nullopt};
421 }
422 
parse_install_mode(std::vector<const char * > argv,InstallMode * install_mode,CmdlineOption * incremental_request,bool * incremental_wait)423 static std::vector<const char*> parse_install_mode(std::vector<const char*> argv,
424                                                    InstallMode* install_mode,
425                                                    CmdlineOption* incremental_request,
426                                                    bool* incremental_wait) {
427     *install_mode = INSTALL_DEFAULT;
428     *incremental_request = CmdlineOption::None;
429     *incremental_wait = false;
430 
431     std::vector<const char*> passthrough;
432     for (auto&& arg : argv) {
433         if (arg == "--streaming"sv) {
434             *install_mode = INSTALL_STREAM;
435         } else if (arg == "--no-streaming"sv) {
436             *install_mode = INSTALL_PUSH;
437         } else if (strlen(arg) >= "--incr"sv.size() && "--incremental"sv.starts_with(arg)) {
438             *incremental_request = CmdlineOption::Enable;
439         } else if (strlen(arg) >= "--no-incr"sv.size() && "--no-incremental"sv.starts_with(arg)) {
440             *incremental_request = CmdlineOption::Disable;
441         } else if (arg == "--wait"sv) {
442             *incremental_wait = true;
443         } else {
444             passthrough.push_back(arg);
445         }
446     }
447     return passthrough;
448 }
449 
parse_fast_deploy_mode(std::vector<const char * > argv,bool * use_fastdeploy,FastDeploy_AgentUpdateStrategy * agent_update_strategy)450 static std::vector<const char*> parse_fast_deploy_mode(
451         std::vector<const char*> argv, bool* use_fastdeploy,
452         FastDeploy_AgentUpdateStrategy* agent_update_strategy) {
453     *use_fastdeploy = false;
454     *agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
455 
456     std::vector<const char*> passthrough;
457     for (auto&& arg : argv) {
458         if (arg == "--fastdeploy"sv) {
459             *use_fastdeploy = true;
460         } else if (arg == "--no-fastdeploy"sv) {
461             *use_fastdeploy = false;
462         } else if (arg == "--force-agent"sv) {
463             *agent_update_strategy = FastDeploy_AgentUpdateAlways;
464         } else if (arg == "--date-check-agent"sv) {
465             *agent_update_strategy = FastDeploy_AgentUpdateNewerTimeStamp;
466         } else if (arg == "--version-check-agent"sv) {
467             *agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
468         } else {
469             passthrough.push_back(arg);
470         }
471     }
472     return passthrough;
473 }
474 
install_app(int argc,const char ** argv)475 int install_app(int argc, const char** argv) {
476     InstallMode install_mode = INSTALL_DEFAULT;
477     auto incremental_request = CmdlineOption::None;
478     bool incremental_wait = false;
479 
480     bool use_fastdeploy = false;
481     FastDeploy_AgentUpdateStrategy agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
482 
483     auto unused_argv = parse_install_mode({argv, argv + argc}, &install_mode, &incremental_request,
484                                           &incremental_wait);
485     auto passthrough_argv =
486             parse_fast_deploy_mode(std::move(unused_argv), &use_fastdeploy, &agent_update_strategy);
487 
488     auto [primary_mode, fallback_mode] =
489             calculate_install_mode(install_mode, use_fastdeploy, incremental_request);
490     if ((primary_mode == INSTALL_STREAM ||
491          fallback_mode.value_or(INSTALL_PUSH) == INSTALL_STREAM) &&
492         best_install_mode() == INSTALL_PUSH) {
493         error_exit("Attempting to use streaming install on unsupported device");
494     }
495 
496     if (use_fastdeploy && get_device_api_level() < kFastDeployMinApi) {
497         fprintf(stderr,
498                 "Fast Deploy is only compatible with devices of API version %d or higher, "
499                 "ignoring.\n",
500                 kFastDeployMinApi);
501         use_fastdeploy = false;
502     }
503     fastdeploy_set_agent_update_strategy(agent_update_strategy);
504 
505     if (passthrough_argv.size() < 2) {
506         error_exit("install requires an apk argument");
507     }
508 
509     auto run_install_mode = [&](InstallMode install_mode, bool silent) {
510         switch (install_mode) {
511             case INSTALL_PUSH:
512                 return install_app_legacy(passthrough_argv.size(), passthrough_argv.data(),
513                                           use_fastdeploy);
514             case INSTALL_STREAM:
515                 return install_app_streamed(passthrough_argv.size(), passthrough_argv.data(),
516                                             use_fastdeploy);
517             case INSTALL_INCREMENTAL:
518                 return install_app_incremental(passthrough_argv.size(), passthrough_argv.data(),
519                                                incremental_wait, silent);
520             case INSTALL_DEFAULT:
521             default:
522                 error_exit("invalid install mode");
523         }
524     };
525     auto res = run_install_mode(primary_mode, fallback_mode.has_value());
526     if (res && fallback_mode.value_or(primary_mode) != primary_mode) {
527         res = run_install_mode(*fallback_mode, false);
528     }
529     return res;
530 }
531 
install_multiple_app_streamed(int argc,const char ** argv)532 static int install_multiple_app_streamed(int argc, const char** argv) {
533     // Find all APK arguments starting at end.
534     // All other arguments passed through verbatim.
535     int first_apk = -1;
536     uint64_t total_size = 0;
537     for (int i = argc - 1; i >= 0; i--) {
538         const char* file = argv[i];
539         if (android::base::EndsWithIgnoreCase(argv[i], ".apex")) {
540             error_exit("APEX packages are not compatible with install-multiple");
541         }
542 
543         if (android::base::EndsWithIgnoreCase(file, ".apk") ||
544             android::base::EndsWithIgnoreCase(file, ".dm") ||
545             android::base::EndsWithIgnoreCase(file, ".fsv_sig")) {
546             struct stat sb;
547             if (stat(file, &sb) == -1) perror_exit("failed to stat \"%s\"", file);
548             total_size += sb.st_size;
549             first_apk = i;
550         } else {
551             break;
552         }
553     }
554 
555     if (first_apk == -1) error_exit("need APK file on command line");
556 
557     const bool use_abb_exec = is_abb_exec_supported();
558     const std::string install_cmd =
559             use_abb_exec ? "package"
560                          : best_install_mode() == INSTALL_PUSH ? "exec:pm" : "exec:cmd package";
561 
562     std::vector<std::string> cmd_args = {install_cmd, "install-create", "-S",
563                                          std::to_string(total_size)};
564     cmd_args.reserve(first_apk + 4);
565     for (int i = 0; i < first_apk; i++) {
566         if (use_abb_exec) {
567             cmd_args.push_back(argv[i]);
568         } else {
569             cmd_args.push_back(escape_arg(argv[i]));
570         }
571     }
572 
573     // Create install session
574     std::string error;
575     char buf[BUFSIZ];
576     {
577         unique_fd fd = send_command(cmd_args, &error);
578         if (fd < 0) {
579             fprintf(stderr, "adb: connect error for create: %s\n", error.c_str());
580             return EXIT_FAILURE;
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         std::vector<std::string> splits = android::base::Split(file, ":");
859 
860         for (const std::string& split : splits) {
861             struct stat sb;
862             if (stat(split.c_str(), &sb) == -1) {
863                 fprintf(stderr, "adb: failed to stat %s: %s\n", split.c_str(), strerror(errno));
864                 goto finalize_multi_package_session;
865             }
866 
867             std::vector<std::string> cmd_args = {
868                     install_cmd,
869                     "install-write",
870                     "-S",
871                     std::to_string(sb.st_size),
872                     session_id_str,
873                     android::base::StringPrintf("%d_%s", i, android::base::Basename(split).c_str()),
874                     "-",
875             };
876 
877             unique_fd local_fd(adb_open(split.c_str(), O_RDONLY | O_CLOEXEC));
878             if (local_fd < 0) {
879                 fprintf(stderr, "adb: failed to open %s: %s\n", split.c_str(), strerror(errno));
880                 goto finalize_multi_package_session;
881             }
882 
883             std::string error;
884             unique_fd remote_fd = send_command(cmd_args, &error);
885             if (remote_fd < 0) {
886                 fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
887                 goto finalize_multi_package_session;
888             }
889 
890             if (!copy_to_file(local_fd.get(), remote_fd.get())) {
891                 fprintf(stderr, "adb: failed to write %s: %s\n", split.c_str(), strerror(errno));
892                 goto finalize_multi_package_session;
893             }
894 
895             read_status_line(remote_fd.get(), buf, sizeof(buf));
896 
897             if (strncmp("Success", buf, 7)) {
898                 fprintf(stderr, "adb: failed to write %s\n", split.c_str());
899                 fputs(buf, stderr);
900                 goto finalize_multi_package_session;
901             }
902         }
903         add_session_cmd_args.push_back(std::to_string(session_id));
904     }
905 
906     {
907         unique_fd fd = send_command(add_session_cmd_args, &error);
908         if (fd < 0) {
909             fprintf(stderr, "adb: connect error for install-add-session: %s\n", error.c_str());
910             goto finalize_multi_package_session;
911         }
912         read_status_line(fd.get(), buf, sizeof(buf));
913     }
914 
915     if (strncmp("Success", buf, 7)) {
916         fprintf(stderr, "adb: failed to link sessions (%s)\n",
917                 android::base::Join(add_session_cmd_args, " ").c_str());
918         fputs(buf, stderr);
919         goto finalize_multi_package_session;
920     }
921 
922     // no failures means we can proceed with the assumption of success
923     success = 0;
924 
925 finalize_multi_package_session:
926     // Commit session if we streamed everything okay; otherwise abandon
927     std::vector<std::string> service_args;
928     if (success == 0) {
929         service_args.push_back(install_cmd);
930         service_args.push_back("install-commit");
931         // If successful, we need to forward args to install-commit
932         for (int i = 1; i < first_package - 1; i++) {
933             if (strcmp(argv[i], "--staged-ready-timeout") == 0) {
934                 service_args.push_back(argv[i]);
935                 service_args.push_back(argv[i + 1]);
936                 i++;
937             }
938         }
939         service_args.push_back(parent_session_id_str);
940     } else {
941         service_args = {install_cmd, "install-abandon", parent_session_id_str};
942     }
943 
944     {
945         unique_fd fd = send_command(service_args, &error);
946         if (fd < 0) {
947             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
948             return EXIT_FAILURE;
949         }
950         read_status_line(fd.get(), buf, sizeof(buf));
951     }
952 
953     if (!strncmp("Success", buf, 7)) {
954         fputs(buf, stdout);
955         if (success == 0) {
956             return 0;
957         }
958     } else {
959         fprintf(stderr, "adb: failed to finalize session\n");
960         fputs(buf, stderr);
961     }
962 
963     session_ids.push_back(parent_session_id);
964     // try to abandon all remaining sessions
965     for (std::size_t i = 0; i < session_ids.size(); i++) {
966         std::vector<std::string> service_args = {
967                 install_cmd,
968                 "install-abandon",
969                 std::to_string(session_ids[i]),
970         };
971         fprintf(stderr, "Attempting to abandon session ID %d\n", session_ids[i]);
972         unique_fd fd = send_command(service_args, &error);
973         if (fd < 0) {
974             fprintf(stderr, "adb: connect error for finalize: %s\n", error.c_str());
975             continue;
976         }
977         read_status_line(fd.get(), buf, sizeof(buf));
978     }
979     return EXIT_FAILURE;
980 }
981 
delete_device_file(const std::string & filename)982 int delete_device_file(const std::string& filename) {
983     // http://b/17339227 "Sideloading a Readonly File Results in a Prompt to
984     // Delete" caused us to add `-f` here, to avoid the equivalent of the `-i`
985     // prompt that you get from BSD rm (used in Android 5) if you have a
986     // non-writable file and stdin is a tty (which is true for old versions of
987     // adbd).
988     //
989     // Unfortunately, `rm -f` requires Android 4.3, so that workaround broke
990     // earlier Android releases. This was reported as http://b/37704384 "adb
991     // install -r passes invalid argument to rm on Android 4.1" and
992     // http://b/37035817 "ADB Fails: rm failed for -f, No such file or
993     // directory".
994     //
995     // Testing on a variety of devices and emulators shows that redirecting
996     // stdin is sufficient to avoid the pseudo-`-i`, and works on toolbox,
997     // BSD, and toybox versions of rm.
998     return send_shell_command("rm " + escape_arg(filename) + " </dev/null");
999 }
1000